Fix SQL Injection (Legacy & Modern) in Nuxt
SQLi in Nuxt isn't a framework flaw; it's a developer skill issue. Whether you're running legacy raw queries in Nitro routes or modern ORMs, failing to parameterize input is an open door for data exfiltration. If you're concatenating strings in your server/api directory, you're essentially handing over your database keys to any script kiddie with a browser.
The Vulnerable Pattern
// server/api/user.get.ts import { defineEventHandler, getQuery } from 'h3'; import mysql from 'mysql2/promise';
export default defineEventHandler(async (event) => { const { id } = getQuery(event); const connection = await mysql.createConnection(process.env.DATABASE_URL); // VULNERABLE: Direct string interpolation allows OOB or union-based injection const [rows] = await connection.query(SELECT * FROM users WHERE id = ${id}); return rows; });
The Secure Implementation
Legacy SQL injection happens when user input from 'getQuery' or 'readBody' is treated as part of the SQL command. To fix this, use 'Prepared Statements'. By using placeholders (?), the SQL engine compiles the query structure first and treats the user input strictly as data, never as executable code. In modern Nuxt stacks, using an ORM like Prisma or Drizzle is preferred as they parameterize queries by default, but always avoid 'raw' query escape hatches unless absolutely necessary and properly sanitized.
// server/api/user.get.ts import { defineEventHandler, getQuery } from 'h3'; import mysql from 'mysql2/promise';
export default defineEventHandler(async (event) => { const { id } = getQuery(event); const connection = await mysql.createConnection(process.env.DATABASE_URL); // SECURE: Using prepared statements with placeholders (?) // The driver handles escaping and type enforcement const [rows] = await connection.execute(‘SELECT * FROM users WHERE id = ?’, [id]); return rows; });
Your Nuxt API
might be exposed to SQL Injection (Legacy & Modern)
74% of Nuxt apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.