GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in Nitro

Nitro's speed doesn't protect you from 1990s-era vulnerabilities. If you're piping 'getQuery' or 'readBody' results directly into raw SQL strings, your database belongs to the first script kiddie with a single quote. In Nitro, the attack surface is usually centered in 'server/api' handlers where H3 event utilities extract untrusted input. To fix this, you must move from string concatenation to strictly parameterized queries or type-safe ORMs.

The Vulnerable Pattern

import { defineEventHandler, getQuery } from 'h3';
import { db } from '../utils/db';

export default defineEventHandler(async (event) => { const { id } = getQuery(event); // VULNERABLE: Direct string interpolation allows UNION-based injection const query = SELECT * FROM users WHERE id = ${id}; const [result] = await db.execute(query); return result; });

The Secure Implementation

The vulnerability stems from treating user-controlled data as code. The 'vulnerable_code' snippet allows an attacker to pass '1 OR 1=1' to dump the entire table. The 'secure_code' demonstrates two solutions: 1. The Modern Approach: Using a Query Builder like Drizzle or Prisma which abstracts SQL generation and enforces parameterization. 2. The Legacy Fix: Using prepared statements with placeholders (?) which ensures the database driver treats the input strictly as data, not executable SQL commands. Always validate and cast types (e.g., Number(id)) before the query hits the driver.

import { defineEventHandler, getQuery, createError } from 'h3';
import { db } from '../utils/db';
import { users } from '../schema';
import { eq } from 'drizzle-orm';

export default defineEventHandler(async (event) => { const { id } = getQuery(event);

if (!id) throw createError({ statusCode: 400, statusMessage: ‘Missing ID’ });

// MODERN FIX: Using Drizzle ORM for type-safe parameterization const result = await db.select().from(users).where(eq(users.id, Number(id)));

// LEGACY FIX (Raw Driver): // const [result] = await db.execute(‘SELECT * FROM users WHERE id = ?’, [id]);

return result; });

System Alert • ID: 4761
Target: Nitro API
Potential Vulnerability

Your Nitro API might be exposed to SQL Injection (Legacy & Modern)

74% of Nitro apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.