Fix Mass Assignment in Nitro
Mass Assignment in Nitro occurs when an attacker manipulates the HTTP request body to include fields that the developer did not intend to be editable. In Nitro's server-side routes, blindly spreading the result of `readBody(event)` into a database update call allows for unauthorized privilege escalation or data corruption. If your backend trustfully maps JSON keys to database columns, you're leaking control over your internal state.
The Vulnerable Pattern
export default defineEventHandler(async (event) => {
const body = await readBody(event);
// VULNERABLE: Blindly spreading the body object allows attackers to pass 'role: "admin"' or 'balance: 9999'
const updatedUser = await db.user.update({
where: { id: event.context.user.id },
data: { ...body }
});
return updatedUser;
});
The Secure Implementation
To kill Mass Assignment, you must enforce a strict allow-list for incoming data. The vulnerable snippet uses the spread operator (`...body`), which merges every key sent by the client into the database query. An attacker can easily intercept the request and add sensitive fields. The secure implementation utilizes Zod for schema validation. By defining an explicit schema, any key not defined in `UpdateProfileSchema` is ignored during the `.parse()` or `.safeParse()` phase. This ensures only the 'displayName' and 'bio' fields reach the database, regardless of what the attacker sends in the payload.
import { z } from 'zod';const UpdateProfileSchema = z.object({ displayName: z.string().min(3).max(50), bio: z.string().max(200).optional() });
export default defineEventHandler(async (event) => { const body = await readBody(event);
// SECURE: Use a schema to parse and strip unknown keys const validatedData = UpdateProfileSchema.parse(body);
const updatedUser = await db.user.update({ where: { id: event.context.user.id }, data: validatedData }); return updatedUser; });
Your Nitro API
might be exposed to Mass Assignment
74% of Nitro 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.