GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in Blitz.js

Blitz.js leverages Prisma, which is generally secure, but developers often introduce SQL injection (SQLi) when dropping down to raw queries for 'performance' or 'complex joins'. If you are using $queryRawUnsafe with string concatenation, you are bypassing all built-in protections. In a full-stack Blitz context, this allows an attacker to dump the entire database, bypass authentication, or achieve RCE depending on the DB engine's configuration.

The Vulnerable Pattern

import db from 'db';

export default async function getLegacyUser(input: { userId: string }) { // CRITICAL VULNERABILITY: String interpolation in $queryRawUnsafe // An attacker can pass ”’ OR ‘1’=‘1” to bypass filters const query = SELECT * FROM "User" WHERE id = '${input.userId}'; const user = await db.$queryRawUnsafe(query); return user; }

The Secure Implementation

The vulnerability stems from treating user-controlled input as executable code. $queryRawUnsafe does exactly what the name implies: it executes a raw string without sanitization. To fix this, use Prisma's $queryRaw tagged template literal. Unlike standard template strings, $queryRaw intercepts the variables and sends them to the database as parameters ($1, $2, etc.), ensuring the DB engine treats them as data, not logic. Additionally, always validate inputs using Zod to ensure the data matches the expected format before it even reaches the database layer.

import db from 'db';
import { z } from 'zod';

export default async function getSecureUser(input: { userId: string }) { // 1. Validation (Defense in Depth) const schema = z.object({ userId: z.string().uuid() }); const { userId } = schema.parse(input);

// 2. MODERN FIX: Use Tagged Template Literals with $queryRaw // Prisma automatically converts this into a parameterized query const user = await db.$queryRawSELECT * FROM "User" WHERE id = ${userId};

// 3. ALTERNATIVE (Best Practice): Use Prisma Client API // const user = await db.user.findUnique({ where: { id: userId } });

return user; }

System Alert • ID: 6091
Target: Blitz.js API
Potential Vulnerability

Your Blitz.js API might be exposed to SQL Injection (Legacy & Modern)

74% of Blitz.js 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.