TExcelTAD
Home › Express & NestJS › Guards & Interceptors

Guards & Interceptors

Express gives you one tool — middleware — for everything that happens around a handler. Nest splits that job into specialised pieces, each running at a fixed point of the request lifecycle:

text
request
  → middleware            (Express-style: logging, cookies, raw request tweaks)
  → guards                may this request proceed?            → 403 if not
  → interceptors (before) code before the handler (timing, caching)
  → pipes                 transform/validate the arguments      → 400 if invalid
  → controller handler → service
  → interceptors (after)  transform the result (wrap, serialize)
  → exception filters     turn any thrown exception into a response
response

Guards: may this request continue?

A guard implements canActivate(context) and returns true (continue) or false (Nest answers 403 Forbidden). It may also throw a more specific exception, such as UnauthorizedException for 401.

ts
// src/auth/auth.guard.ts
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { TokenService } from './token.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly tokens: TokenService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    const user = type === 'Bearer' ? this.tokens.verify(token) : null;
    if (!user) throw new UnauthorizedException();
    request.user = user;   // available to later guards and the handler
    return true;
  }
}

Guards, unlike Express middleware, know which handler will run (context.getHandler(), context.getClass()). That's what makes role metadata possible:

ts
// src/auth/roles.decorator.ts
import { Reflector } from '@nestjs/core';
export const Roles = Reflector.createDecorator<string[]>();

// src/auth/roles.guard.ts
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride(Roles, [context.getHandler(), context.getClass()]);
    if (!required) return true;                         // no @Roles → open to any logged-in user
    const { user } = context.switchToHttp().getRequest();
    return required.some((role) => user?.roles?.includes(role));
  }
}

// usage
@Controller('admin')
@UseGuards(AuthGuard, RolesGuard)       // guards run in this order
export class AdminController {
  @Get('stats')
  @Roles(['admin'])
  stats() { return { users: 42 }; }
}
bash · try it yourself
curl localhost:3000/admin/stats
curl -H "Authorization: Bearer <editor-token>" localhost:3000/admin/stats
curl -H "Authorization: Bearer <admin-token>" localhost:3000/admin/stats
{"message":"Unauthorized","statusCode":401}
{"message":"Forbidden resource","error":"Forbidden","statusCode":403}
{"users":42}
Binding Scope
@UseGuards(G) on a method one route
@UseGuards(G) on a controller all routes of the controller
{ provide: APP_GUARD, useClass: G } in a module every route in the app (supports DI)

Tip: A common pattern is a global AuthGuard plus a @Public() decorator for the few open routes (login, health). The guard checks the metadata and skips authentication when it finds @Public(). Secure by default!

Simulating the guard chain

This playground models the same chain — authentication, then role check — with metadata attached to handlers:

ts · try it yourself
type User = { id: string; roles: string[] };
type Request = { headers: Record<string, string>; user?: User };
type Handler = { name: string; roles?: string[] };
class HttpError extends Error { constructor(readonly status: number, message: string) { super(message); } }

const tokens: Record<string, User> = { 't-ana': { id: 'ana', roles: ['admin'] }, 't-bo': { id: 'bo', roles: ['editor'] } };

const authGuard = (req: Request) => {
  const user = tokens[req.headers.authorization?.replace('Bearer ', '') ?? ''];
  if (!user) throw new HttpError(401, 'Unauthorized');
  req.user = user;
  return true;
};
const rolesGuard = (req: Request, handler: Handler) =>
  !handler.roles || handler.roles.some((r) => req.user?.roles.includes(r));

function handle(req: Request, handler: Handler, guards: ((r: Request, h: Handler) => boolean)[]) {
  try {
    for (const guard of guards) {
      if (!guard(req, handler)) throw new HttpError(403, 'Forbidden resource');
    }
    return `200 ${handler.name} ran for ${req.user?.id}`;
  } catch (e) {
    const err = e as HttpError;
    return `${err.status} ${err.message}`;
  }
}

const stats: Handler = { name: 'stats', roles: ['admin'] };
const profile: Handler = { name: 'profile' };
const guards = [authGuard, rolesGuard];

console.log(handle({ headers: {} }, stats, guards));
console.log(handle({ headers: { authorization: 'Bearer t-bo' } }, stats, guards));
console.log(handle({ headers: { authorization: 'Bearer t-bo' } }, profile, guards));
console.log(handle({ headers: { authorization: 'Bearer t-ana' } }, stats, guards));
401 Unauthorized
403 Forbidden resource
200 profile ran for bo
200 stats ran for ana

Interceptors: around the handler

An interceptor wraps the handler call. next.handle() returns an RxJS Observable of the handler's result, so you can run code before, after, or transform the value:

ts
// src/common/envelope.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, map, tap } from 'rxjs';

@Injectable()
export class EnvelopeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const started = performance.now();
    const { method, url } = context.switchToHttp().getRequest();
    return next.handle().pipe(
      map((data) => ({ data })),                                            // wrap every response
      tap(() => console.log(`${method} ${url} ${(performance.now() - started).toFixed(1)}ms`)),
    );
  }
}

// bind globally in main.ts
app.useGlobalInterceptors(new EnvelopeInterceptor());
bash · try it yourself
curl localhost:3000/cats/1
{"data":{"id":1,"name":"Mochi","age":3}}

Typical uses:

Interceptor Does
response envelope { data: … } around every result
ClassSerializerInterceptor (built in) applies @Exclude() — e.g. hide passwordHash
timing / logging measure handler duration
caching (CacheInterceptor) return a cached result without calling the handler
timeout timeout(5000) operator → 408/504

Interceptors as plain functions

Under the RxJS surface, an interceptor is "a function that receives the next step and returns a wrapped one". Composition makes the order visible — the first interceptor is the outermost layer:

ts · try it yourself
type Next = () => Promise<unknown>;
type Interceptor = (next: Next) => Promise<unknown>;

const log: string[] = [];

const timing: Interceptor = async (next) => {
  log.push('timing: before');
  const result = await next();
  log.push('timing: after');
  return result;
};

const envelope: Interceptor = async (next) => {
  log.push('envelope: before');
  const result = await next();
  log.push('envelope: after');
  return { data: result };
};

function compose(interceptors: Interceptor[], handler: Next): Next {
  return interceptors.reduceRight<Next>((inner, icpt) => () => icpt(inner), handler);
}

const handler: Next = async () => {
  log.push('handler');
  return { id: 1, name: 'Mochi' };
};

const result = await compose([timing, envelope], handler)();
console.log(log.join('\n'));
console.log(result);
timing: before
envelope: before
handler
envelope: after
timing: after
{ data: { id: 1, name: 'Mochi' } }

Guard, interceptor or middleware?

Need Use
reject unauthenticated / unauthorised requests guard
transform the response, measure time, cache interceptor
validate or convert arguments pipe
work on the raw request before routing (e.g. cookie-parser, helmet) middleware
format errors exception filter (next lesson)

Test yourself

What does Nest respond when a guard's canActivate returns false?

  1. 401 Unauthorized
  2. 403 Forbidden
  3. 404 Not Found
  4. 500

Which runs first for an incoming request?

  1. Pipes
  2. Interceptors
  3. Guards
  4. Exception filters

What does next.handle() return inside an interceptor?

  1. The raw Express response
  2. An Observable of the handler's result
  3. A boolean
  4. The request object