Fix SQL Injection (Legacy & Modern) in SvelteKit
SQL Injection in SvelteKit isn't a framework flaw; it's a developer skill issue. When you pipe url.searchParams or formData directly into a raw query string within your +page.server.js actions, you are handing over the keys to your database. Whether you are using legacy pg drivers or modern TypeScript-first ORMs, the fix remains constant: absolute separation of code and data.
The Vulnerable Pattern
// src/routes/admin/users/+page.server.js
export async function load({ url, locals }) {
const userId = url.searchParams.get('id');
// CRITICAL VULNERABILITY: Direct string interpolation
// Payload: ?id=1' OR '1'='1
const query = `SELECT * FROM users WHERE id = '${userId}'`;
const result = await locals.db.execute(query);
return { user: result.rows[0] };
}
The Secure Implementation
The vulnerable code allows an attacker to manipulate the SQL structure by injecting control characters (like single quotes) into the template literal. The fix involves using Prepared Statements where the database driver sends the query template and the user data in separate packets. In the secure 'Legacy' example, the $1 placeholder ensures the DB engine treats the input strictly as a string literal. In the 'Modern' example, Drizzle ORM abstracts the parameterization, making it impossible to accidentally concatenate raw input into the WHERE clause.
// Option 1: Parameterized Query (Standard) export async function load({ url, locals }) { const userId = url.searchParams.get('id'); const query = 'SELECT * FROM users WHERE id = $1'; const result = await locals.db.query(query, [userId]); return { user: result.rows[0] }; }// Option 2: Modern Drizzle ORM (Type-safe & Secure) import { eq } from ‘drizzle-orm’; import { users } from ‘$lib/db/schema’;
export async function load({ url, locals }) { const id = url.searchParams.get(‘id’); const user = await locals.db.select().from(users).where(eq(users.id, id)); return { user }; }
Your SvelteKit API
might be exposed to SQL Injection (Legacy & Modern)
74% of SvelteKit 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.