Securing JSON Responses in NestJS with @Exclude()
4 min read · 2024
When you return a user entity from a NestJS controller, it serializes every property — including the ones you never meant to expose. Passwords, refresh tokens, and internal flags can quietly leak.
The fix is the @Exclude() decorator from class-transformer. Wrap your entity, mark the sensitive fields, and apply the ClassSerializerInterceptor globally:
import { Exclude } from 'class-transformer';
export class User {
id: string;
email: string;
@Exclude() password: string;
@Exclude() refreshToken?: string;
}
Then in main.ts add the interceptor so every response runs through it. You now ship by default secure — adding a new sensitive field is a one-decorator job, not a one-incident postmortem.