GuardAPI Logo
GuardAPI

Fix Mass Assignment in Next.js

Mass Assignment in Next.js occurs when you blindly spread request bodies or form data into your database layer. Attackers exploit this to overwrite sensitive fields like 'role', 'isAdmin', or 'permissions' by injecting unexpected keys into the JSON payload. If you're using Prisma, Mongoose, or Drizzle and passing the raw input object directly to an update or create call, you're pwned.

The Vulnerable Pattern

export async function POST(req: Request) {
  const body = await req.json();
  // VULNERABLE: Spreading the entire body allows an attacker to send { "role": "admin" }
  const updatedUser = await prisma.user.update({
    where: { id: body.id },
    data: { ...body }
  });
  return Response.json(updatedUser);
}

The Secure Implementation

The fix is mandatory whitelisting. Instead of using the spread operator on untrusted input, use a schema validation library like Zod or manually map properties to a new object. By defining a strict schema, any extra fields injected by an attacker (like 'isAdmin: true') are ignored during the parsing phase, ensuring only the intended fields reach your database query. This decouples your internal data model from the public API contract.

import { z } from 'zod';

const UpdateProfileSchema = z.object({ name: z.string().min(2), bio: z.string().max(160).optional(), });

export async function POST(req: Request) { const json = await req.json(); // SECURE: Parse and validate. Only ‘name’ and ‘bio’ are extracted. const validatedData = UpdateProfileSchema.parse(json);

const updatedUser = await prisma.user.update({ where: { id: json.id }, data: validatedData }); return Response.json(updatedUser); }

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

Your Next.js API might be exposed to Mass Assignment

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.