Advanced Web, API & Modern Stack
NestJS Security Deep Dive
Guards, DTO validation, and the auth pitfalls specific to NestJS.
NestJS structures Express/Fastify apps with modules, guards, pipes, and DTOs. Its abstractions are great for security — when used correctly. The common bugs come from guards/validation that are assumed but not actually applied.
Where NestJS apps go wrong
- Missing/incorrect Guards — an endpoint without @UseGuards (or a guard that returns true by default) = no auth.
- No global ValidationPipe with whitelist:true → mass assignment; extra body fields flow into your DTO/entity.
- Weak role checks — a custom RolesGuard that trusts a client-supplied header or an unverified JWT claim.
- Over-exposed responses — returning full entities (password hashes, tokens) instead of a response DTO.
- Insecure JWT config — no expiry, weak secret, or not verifying issuer/audience (see JWT Attacks).
// Enable strict DTO validation globally (blocks mass assignment)
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // strip unknown properties
forbidNonWhitelisted: true // reject unexpected fields
}));