QA
Senior LevelExpress JS

How do you defend Express endpoints against Mass Assignment (Over-Posting) attacks using DTOs?

❓ Interview Prompt: Explain Mass Assignment vulnerabilities, attacker field injection (role: "admin"), and enforcing DTO whitelisting with Zod schemas.

Mass Assignment (Over-Posting) occurs when a controller passes raw 'req.body' directly into a database create/update query ('prisma.user.create({ data: req.body })'). An attacker POSTs '{ "name": "Bob", "role": "admin", "isVerified": true }', elevating their privileges!

Defense Strategy:

Enforce strict Data Transfer Object (DTO) whitelisting using Zod schemas. Only pass explicitly parsed schema attributes to database layers!

Code Implementation Example

typescript
import { z } from 'zod';

// Strict DTO Schema whitelisting ONLY allowed user-editable fields
const CreateUserDTO = z.object({
  email: z.string().email(),
  password: z.string().min(8)
  // 'role' and 'isVerified' are intentionally EXCLUDED from DTO!
});

app.post('/api/register', async (req, res) => {
  // Safe: Strips any un-declared fields (like role: 'admin') from req.body!
  const safeData = CreateUserDTO.parse(req.body);
  const user = await db.user.create({ data: safeData });
  res.status(201).json(user);
});
💡Blocking Mass Assignment field injection attacks using Zod DTO schemas.
🎯 Interview Key Takeaway

Never pass raw req.body directly to database queries. Enforce DTO whitelisting using Zod schemas to prevent Mass Assignment attacks.

#Mass Assignment#DTO#Security#Senior
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?