Guards interceptors and filters
Framework lane: NestJS 11.x candidate, TypeScript legacy decorators and emitDecoratorMetadata, compatible reflect-metadata and RxJS. Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages. A decorator such as @Controller attaches framework metadata; a TypeScript annotation describes a compile-time contract. The full TypeScript chapter follows this introduction. Use a reviewed Nest TypeScript project, not node directly on the .ts file.
Framework example — staged
import { CanActivate, Controller, Get, Injectable, UseGuards } from '@nestjs/common';@Injectable()class DenyDemoGuard implements CanActivate { canActivate() { return false; }}@Controller('staff')@UseGuards(DenyDemoGuard)export class StaffController { @Get('stock') stock() { return { count:4 }; }}Expected behavior (not observed): Partial controller: register with the approved module. GET /staff/stock should be denied with 403 and never return count. Replace the illustrative guard only with reviewed real authorization.
How it works
For ordinary HTTP flow, middleware precedes guards, then interceptors enter, pipes resolve arguments and the controller executes. Interceptors can map returned values on the way out. Exception filters handle uncaught failures; they are not an unconditional final stage. Guards may reject before the handler, and interceptors may short-circuit. This fixture uses a denying guard only, to illustrate the boundary without real authentication.
Practice the underlying idea without dependencies
function handle(allowed) { const trace=['guard']; if(!allowed) return {status:403,trace}; trace.push('handler'); return {status:200,trace};}console.log(JSON.stringify([handle(false),handle(true)]));Run node main.mjs in a disposable directory. Expected output:
[{"status":403,"trace":["guard"]},{"status":200,"trace":["guard","handler"]}]This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
Do not put a permission check solely in a response interceptor after a protected write. A filter is not a universal catch-all for detached work. The local trace is a conceptual control-flow example, not Nest execution.
Apply it yourself
Draw the normal and guard-denied lifecycle and identify where DTO validation, public response mapping and exception redaction belong.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Guards interceptors and filters — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Which component should deny a request before the handler runs?
When does an interceptor’s response mapping normally occur?
When does an exception filter handle a failure?