GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Gatsby

Gatsby Functions are the primary vector for NoSQL injection in the Gatsby ecosystem. When building dynamic APIs or serverless handlers, developers often pipe 'req.body' or 'req.query' directly into MongoDB query filters. An attacker can supply a JSON object containing MongoDB operators like '$gt' or '$ne' instead of a string, effectively bypassing authentication or exfiltrating the entire database. If you aren't sanitizing your inputs to strict types, your data layer is compromised.

The Vulnerable Pattern

export default async function handler(req, res) {
  const { username, password } = req.body;
  // VULNERABLE: Attacker sends { "password": { "$ne": "" } }
  // This results in finding the first user where password is not empty.
  const user = await db.collection('users').findOne({
    username: username,
    password: password
  });
  if (user) return res.status(200).json({ status: 'success' });
  return res.status(401).json({ status: 'fail' });
}

The Secure Implementation

The vulnerability stems from JavaScript's dynamic typing and MongoDB's query syntax. By passing a JSON object instead of a string, an attacker injects query operators. To remediate, you must enforce strict typing. Using a library like Zod or Joi ensures that 'req.body.password' is a primitive string and not a malicious object. If you cannot use a validation library, explicitly cast every input to a string using 'String()' or use the 'mongo-sanitize' middleware to strip keys starting with '$' from the input.

import { z } from 'zod';

const schema = z.object({ username: z.string(), password: z.string() });

export default async function handler(req, res) { // SECURE: Validate input against a strict schema const result = schema.safeParse(req.body); if (!result.success) return res.status(400).json({ error: ‘Invalid input’ });

const { username, password } = result.data;

// Alternatively, force type casting to string: // const username = String(req.body.username);

const user = await db.collection(‘users’).findOne({ username: username, password: password }); if (user) return res.status(200).json({ status: ‘success’ }); return res.status(401).json({ status: ‘fail’ }); }

System Alert • ID: 4412
Target: Gatsby API
Potential Vulnerability

Your Gatsby API might be exposed to NoSQL Injection

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