GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Next.js

Stop trusting raw request objects. In Next.js API routes, passing unsanitized 'req.body' or 'req.query' directly into MongoDB/Mongoose filters is a critical vulnerability. Attackers leverage operator injection—using objects like {'$gt': ''}—to bypass authentication logic or exfiltrate data. If you aren't enforcing types, you're pwned.

The Vulnerable Pattern

// pages/api/auth.js
import dbConnect from '../../lib/db';
import User from '../../models/User';

export default async function handler(req, res) { await dbConnect(); // VULNERABLE: Attacker sends { “user”: { “$ne”: null }, “pass”: { “$ne”: null } } // This bypasses the check and logs in as the first user in the collection. const user = await User.findOne(req.body); if (user) return res.status(200).json({ login: true }); res.status(401).json({ login: false }); }

The Secure Implementation

The vulnerability exists because NoSQL databases like MongoDB accept objects as query parameters. When you pass 'req.body' directly, an attacker can replace a string with a query operator object. The fix involves two layers: 1. Input Validation: Use a library like Zod to ensure inputs are strictly strings, not objects. 2. Explicit Querying: Never pass a root object to 'findOne()'; instead, map validated primitives to specific schema keys. This prevents the query engine from interpreting malicious operators as logic.

// pages/api/auth.js
import dbConnect from '../../lib/db';
import User from '../../models/User';
import { z } from 'zod';

// Enforce strict schema validation const AuthSchema = z.object({ user: z.string(), pass: z.string() });

export default async function handler(req, res) { await dbConnect();

const validation = AuthSchema.safeParse(req.body); if (!validation.success) return res.status(400).json({ error: ‘Invalid input’ });

const { user, pass } = validation.data;

// SECURE: Using explicit keys and validated string primitives const account = await User.findOne({ username: user, password: pass }).lean();

if (account) return res.status(200).json({ login: true }); res.status(401).json({ login: false }); }

System Alert • ID: 8587
Target: Next.js API
Potential Vulnerability

Your Next.js API might be exposed to NoSQL Injection

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