NestJS 11 cheatsheet
NestJS 11: Validation, guards and interceptors
7 common NestJS 11 tasks.
Describe and validate a request body
Use class-validator decorators on a DTO class.
export class CreateCatDto {
@IsString()
@MinLength(2)
name: string;
@IsInt()
@Min(0)
age: number;
}
Enable validation globally
Validate and transform every request body. whitelist removes properties the DTO doesn't declare.
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
Protect routes with a guard
A guard decides whether a request may proceed. Throw or return false to deny it.
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return Boolean(request.headers.authorization);
}
}
@UseGuards(AuthGuard)
@Get('profile')
profile() {}
Run code around handlers
An interceptor can log, transform responses or time requests.
@Injectable()
export class TimingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const start = Date.now();
return next.handle().pipe(tap(() => console.log(`took ${Date.now() - start}ms`)));
}
}
Customize error responses
A filter turns exceptions into the responses you want.
@Catch(HttpException)
export class HttpErrorFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
response.status(exception.getStatus()).json({ message: exception.message });
}
}
Enable CORS
Allow browser apps on other origins to call the API.
const app = await NestFactory.create(AppModule);
app.enableCors({ origin: 'https://app.example.com' });
Generate OpenAPI docs
Serve an OpenAPI document and Swagger UI. Install @nestjs/swagger first.
const config = new DocumentBuilder().setTitle('Cats API').setVersion('1.0').build();
SwaggerModule.setup('docs', app, SwaggerModule.createDocument(app, config));