What is the NestJS request lifecycle order?

A NestJS request passes through a fixed sequence of stages. Each stage receives different inputs and makes different guarantees, so the order determines what each component can know and what it can stop.

  1. Incoming request arrives from the underlying HTTP adapter.
  2. Middleware runs first: globally bound middleware, then module-bound middleware. At this point Nest has not selected a route handler, so middleware sees only the raw request and response.
  3. Guards run in order: global, then controller, then route. Guards have the execution context, so they know which handler will run. They return a yes/no decision on whether the request proceeds.
  4. Interceptors (before) run global, then controller, then route. They wrap the handler call.
  5. Pipes run global, then controller, then route, then parameter. They transform and validate the handler's arguments.
  6. Route handler executes, usually calling into services.
  7. Interceptors (after) process the result in reverse order (route, controller, global) as the response stream unwinds.
  8. Exception filters take over if anything above throws. Filters resolve from the most specific scope outward, and the first matching filter handles the error.
  9. Response is sent.

Each later stage relies on what the earlier ones have established. Guards can make decisions per handler because routing has already happened. Pipes can assume the caller is authorized. Interceptors can measure or reshape the handler's output because they sit on both sides of it.

This model matters most to backend and platform engineers who own cross-cutting concerns such as authentication, logging, validation, and error shaping. If one of these concerns runs at the wrong stage, it either lacks the context it needs or runs too late to block the request.

        Incoming request (HTTP adapter)
                      │
                      ▼
 ┌─────────────────────────────────────────┐
 │ Middleware     global → module          │ raw req/res, no route yet
 └────────────────────┬────────────────────┘
                      ▼
 ┌─────────────────────────────────────────┐
 │ Guards         global → ctrl → route    │ knows handler; allow/deny
 └────────────────────┬────────────────────┘
                      ▼
 ┌─────────────────────────────────────────┐
 │ Interceptors   global → ctrl → route    │ before handler (wraps it)
 └────────────────────┬────────────────────┘
                      ▼
 ┌─────────────────────────────────────────┐
 │ Pipes   global → ctrl → route → param   │ transform/validate args
 └────────────────────┬────────────────────┘
                      ▼
 ┌─────────────────────────────────────────┐
 │ Route handler  → services               │
 └────────────────────┬────────────────────┘
                      ▼
 ┌─────────────────────────────────────────┐
 │ Interceptors   route → ctrl → global    │ after handler, reverse order
 └────────────────────┬────────────────────┘
             success  │   any stage throws
                      ▼          ▼
                  Response ◄── Exception filters
                               (specific scope → outward; first match)

The NestJS request lifecycle: middleware, guards, interceptors, pipes and the handler run in a fixed order, interceptors unwind in reverse, and exception filters handle anything thrown before the response is sent.

What can middleware, guards, interceptors, pipes and filters each see?

Each stage receives a different set of arguments, and those arguments limit what the code at that stage can know.

Middleware receives the platform's request and response objects and a next() function. It runs before Nest has resolved a route handler, so it has no ExecutionContext. It cannot tell which controller method will run or what decorators are on it. It can read headers, cookies and the URL, but it cannot see a @Roles('admin') annotation.

Guards and interceptors receive an ExecutionContext. Its getHandler() and getClass() methods return the target method and controller, and Reflector reads metadata attached to them. Interceptors also receive a CallHandler. They can act before the handler runs, and they can transform the result through the returned observable.

Pipes see a single argument value at a time, plus ArgumentMetadata: the source (body, query, param or custom), the declared type, and the property name. They do not see the rest of the request.

Exception filters receive the thrown exception and an ArgumentsHost. They can reach the request and response, but their job is translating a failure, not making routing decisions.

Component Primary input Knows the handler? Reads route metadata?
Middleware req, res, next() No No
Guard ExecutionContext Yes Yes, via Reflector
Interceptor ExecutionContext, CallHandler Yes Yes, via Reflector
Pipe value, ArgumentMetadata Indirectly Only argument metadata
Filter exception, ArgumentsHost Through the host Rarely needed

Because of these inputs, placement is not a matter of taste. Role checks that depend on decorators must run in a guard, because middleware cannot see decorators. Validating a DTO requires its declared type, and pipes are the stage that receives it.

How do guards and interceptors work, and how do they differ?

A guard implements canActivate(context) and returns a boolean, a Promise<boolean> or an Observable<boolean>. That return value answers one question: may this request reach the handler? A guard cannot transform the request or the response, which keeps authorization logic narrow and testable.

The typical pattern pairs a @Roles() decorator, built on SetMetadata, with a guard that reads the metadata through Reflector. Calling reflector.getAllAndOverride() with both context.getHandler() and context.getClass() lets a method-level annotation override a controller-level one. This is why authorization belongs in a guard: the ExecutionContext exposes the target handler, and middleware has no equivalent.

If the guard returns false, Nest throws a ForbiddenException, which produces a 403. To return a different status, throw the exception yourself. For example, throw UnauthorizedException when no credentials are present, so clients can tell "not logged in" (401) apart from "not allowed" (403).

An interceptor implements intercept(context, next) and must return an Observable. The handler runs only when you call next.handle(), which returns an RxJS Observable of the handler's result. A timing interceptor records a timestamp, calls next.handle(), and logs the elapsed time inside tap().

Put post-handler logic in operators such as tap and map. Code placed after the next.handle() call runs immediately, before the handler has produced a value, so it would measure or transform nothing.

Common uses for interceptors:

  • Response mapping with map, for example wrapping results in an envelope.
  • Timeouts with the timeout operator.
  • Error remapping with catchError.
  • Cache short-circuiting: return of(cached) and skip next.handle() entirely.
import { CallHandler, CanActivate, ExecutionContext, Injectable, NestInterceptor, SetMetadata, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable, tap } from 'rxjs';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    // Method-level @Roles() overrides controller-level @Roles()
    const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!required) return true; // no @Roles() metadata: route is open

    const { user } = context.switchToHttp().getRequest();
    // No credentials: throw 401 ourselves instead of the default 403
    if (!user) throw new UnauthorizedException();

    // Returning false makes Nest throw ForbiddenException (403)
    return required.some((role) => user.roles?.includes(role));
  }
}

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const start = Date.now();
    const name = `${context.getClass().name}.${context.getHandler().name}`;
    // The handler runs only when next.handle() is subscribed; tap fires after it emits.
    // Code placed after this return path would run before the handler produced a value.
    return next.handle().pipe(tap(() => console.log(`${name} took ${Date.now() - start}ms`)));
  }
}

A @Roles() decorator read via Reflector in a guard that returns a boolean (or throws UnauthorizedException for a 401), alongside a timing interceptor that measures the handler inside tap() on the Observable from next.handle().

How do pipes and exception filters fit into the pipeline?

Pipes are the last step before the handler runs. Each pipe receives one argument, such as @Body(), @Param('id') or @Query(), and either returns a transformed value or throws. ParseIntPipe turns the string "42" into the number 42 and rejects "abc" with a 400. ValidationPipe uses class-transformer to turn the plain body into an instance of your DTO class. It then runs the class-validator decorators on that instance. With whitelist enabled, it strips properties the DTO does not declare.

Pipes run after guards and after the pre-handler part of interceptors, so an authorization guard sees the raw, unvalidated request. If a guard reads request.body.tenantId, it gets whatever the client sent: possibly a string, possibly missing, never coerced. Guards should either rely on trusted data such as a verified token, or validate the fields they read themselves.

Exception filters catch anything thrown during the request that nothing else handled. That includes errors from guards, pipes, interceptors and the handler. Nest resolves filters by scope: route first, then controller, then global. The most specific filter whose @Catch() matches the exception type handles it. Filters do not chain, so a route filter that catches an error prevents the global filter from seeing it.

Exceptions thrown in middleware also reach Nest's exception layer. Route and controller filters are not resolved at that point, so only global filters and the built-in handler apply.

If an interceptor's catchError turns an error into a normal value, no filter ever runs. If it rethrows, the filter sees the new error, not the original.

import { ArgumentsHost, BadRequestException, Body, CanActivate, Catch, Controller, ExceptionFilter, ExecutionContext, Injectable, Param, ParseIntPipe, Post, UseFilters, UseGuards, ValidationPipe } from '@nestjs/common';
import { IsInt, IsString, Min } from 'class-validator';
import { Response } from 'express';

class CreateOrderDto {
  @IsString() sku!: string;
  @IsInt() @Min(1) quantity!: number;
}

@Injectable()
class TenantGuard implements CanActivate {
  canActivate(ctx: ExecutionContext): boolean {
    const req = ctx.switchToHttp().getRequest();
    // Runs BEFORE pipes: req.body and req.params are still raw and unvalidated.
    // Base the decision on req.user, set by earlier auth middleware from a verified token.
    return typeof req.user?.tenantId === 'string';
  }
}

// Only handles BadRequestException. A ForbiddenException from the guard
// does not match, so it falls through to global filters or the built-in handler.
@Catch(BadRequestException)
class ValidationErrorFilter implements ExceptionFilter {
  catch(exception: BadRequestException, host: ArgumentsHost) {
    // Route-scoped and most specific, so global filters never see this error.
    host.switchToHttp().getResponse<Response>().status(422).json({ errors: exception.getResponse() });
  }
}

@Controller('tenants/:tenantId/orders')
@UseGuards(TenantGuard)
export class OrdersController {
  @Post()
  @UseFilters(ValidationErrorFilter)
  create(
    @Param('tenantId', ParseIntPipe) tenantId: number, // "42" -> 42, "abc" -> BadRequestException
    @Body(new ValidationPipe({ whitelist: true, transform: true })) dto: CreateOrderDto, // undeclared props stripped
  ) {
    return { tenantId, sku: dto.sku, quantity: dto.quantity };
  }
}

A guard runs before the parameter pipes, so it sees the raw request. ParseIntPipe and ValidationPipe throw BadRequestException, and a route-scoped filter catches that error before any global filter can see it.

How should you bind and register each component?

Each enhancer can be bound at three scopes: method (decorator on a handler), controller (decorator on the class), and global. Method and controller bindings are explicit and easy to find. Global bindings need more thought.

useGlobalX() vs APP_* providers

app.useGlobalGuards(), useGlobalInterceptors(), useGlobalPipes() and useGlobalFilters() take instances you construct yourself in main.ts. That code runs outside the module graph, so the container cannot inject anything into those instances. A guard that needs a JwtService, or a filter that needs a logger or config provider, either receives its dependencies by hand or does not work.

The alternative is to register the class as a provider under the APP_GUARD, APP_INTERCEPTOR, APP_PIPE or APP_FILTER token from @nestjs/core. Nest instantiates it inside the module, resolves its constructor dependencies, and still applies it globally. This holds no matter which module declares it.

Middleware

Middleware that needs DI is bound in a module that implements NestModule. In its configure(consumer: MiddlewareConsumer) method, call consumer.apply(...), chain .exclude(...) for paths or route objects to skip, then call .forRoutes(...) with paths, controllers or route objects. app.use() is global but has the same DI limitation as useGlobalX().

The trade-off

APP_* providers fix DI but hide global behavior in whichever module declared them. Keep them in one predictable place, such as AppModule or a dedicated core module. Also, in hybrid apps, bindings made with useGlobalX() are not set up for gateways and connected microservices, and middleware only runs for HTTP. Check each transport explicitly instead of assuming the HTTP pipeline covers it.

// app.module.ts: keep every global enhancer in one predictable place
import { MiddlewareConsumer, Module, NestModule, RequestMethod, ValidationPipe } from '@nestjs/common';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
import { JwtAuthGuard } from './auth/jwt-auth.guard'; // injects JwtService
import { AuditInterceptor } from './audit/audit.interceptor'; // injects a logger
import { HttpErrorFilter } from './errors/http-error.filter';
import { RequestIdMiddleware } from './common/request-id.middleware';
import { OrdersController } from './orders/orders.controller';

@Module({
  imports: [JwtModule.register({ secret: 'replace-with-env-secret' })],
  controllers: [OrdersController],
  providers: [
    // Nest constructs these inside the module, so constructor DI works,
    // yet they apply to every route, as useGlobalX() would.
    // Contrast: app.useGlobalGuards(new JwtAuthGuard(/* JwtService? */)) in main.ts
    // runs outside the container, so you would have to wire dependencies by hand.
    { provide: APP_GUARD, useClass: JwtAuthGuard },
    { provide: APP_INTERCEPTOR, useClass: AuditInterceptor },
    { provide: APP_FILTER, useClass: HttpErrorFilter },
    { provide: APP_PIPE, useValue: new ValidationPipe({ whitelist: true }) },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(RequestIdMiddleware) // resolved by the container, so it can inject providers
      .exclude(
        { path: 'health', method: RequestMethod.GET }, // skip liveness probes
      )
      .forRoutes(OrdersController, { path: 'admin/*', method: RequestMethod.ALL });
    // Middleware runs only for HTTP. Gateways and connected microservices
    // in a hybrid app do not pass through it, so verify each transport separately.
  }
}

An AppModule that registers a guard, interceptor, filter and pipe globally through APP_ providers so their dependencies are injected, and binds DI-aware middleware with MiddlewareConsumer, exclude and forRoutes.*

Which layer should handle which concern?

Concern Layer Why this layer
Request IDs, correlation headers Middleware Runs first, so every later log line can include the ID
Raw body, header normalisation Middleware Works on the transport request before handler context matters
Authentication, authorization Guards Sees handler metadata such as roles or a public-route marker
Logging, metrics, response envelopes Interceptors Wraps the handler, so it can time it and transform its output
Caching, timeouts Interceptors Can skip the handler or cancel the returned stream
Input validation, coercion Pipes Runs per argument with the target type available
Error-to-HTTP mapping Exception filters Catches what every other layer throws

Some concerns could sit in either of two layers, and you should pick one. Authentication can live in middleware or a guard. Use a guard when access rules depend on the route, because middleware cannot read handler metadata. Request logging can live in middleware or an interceptor. Use middleware if you need to record requests that guards reject, since an interceptor never runs for them. Use an interceptor if you want handler-level timing.

Give each concern exactly one owner, then pass the result forward on the request object. If middleware decodes a token and a guard decodes it again, you pay for parsing twice. The two copies can also drift apart, for example when one checks expiry and the other doesn't.

Have the guard verify the token once and attach a typed principal, such as request.user, declared through interface augmentation. Handlers then read that principal through a custom parameter decorator instead of parsing headers again. When a reviewer needs to know where tokens are checked, there is one answer.

When should you avoid each layer?

Each layer has a failure mode that tends to appear once the codebase grows.

Authorization in middleware. Middleware runs before Nest resolves the route handler, so it cannot read metadata set by decorators such as a roles decorator. Authorizing there means matching path strings, and those patterns drift from the controllers. A route can be renamed or a new endpoint added, and the middleware check silently stops covering it. Keep middleware for authentication parsing and request-wide concerns. Put authorization in guards, where the handler and its metadata are available.

Body-based authorization in guards. Guards run before pipes, so request.body is still raw client input when the guard sees it. A guard that checks "does this user own body.projectId?" is trusting an unvalidated value with an unknown type. Either validate that field inside the guard, or move ownership checks into the service layer, where the DTO has already been transformed and validated.

Overloaded interceptors. An interceptor that chains caching, retries, timeouts and response mapping with nested RxJS operators is hard to trace. A catchError that returns a fallback value can also swallow an exception before any exception filter sees it. Split unrelated concerns into separate interceptors. Rethrow errors unless suppressing them is intended.

Response shaping with @Res(). When a handler injects the platform response object, Nest stops managing the response, and mapping interceptors have nothing to transform. Use @Res({ passthrough: true }) if you need the raw object for headers or cookies but still want the handler to return a value.

Non-HTTP transports. Middleware does not run for WebSocket gateways or microservice handlers. Guards and interceptors do run there, but they must switch the context with switchToWs() or switchToRpc(). For GraphQL, they must use GqlExecutionContext. If a guard assumes switchToHttp(), it will read the wrong object on those transports.

How do you debug ordering issues in the NestJS pipeline?

The fastest way to settle an ordering dispute is to stop reasoning about it and print it. Give each component a single console.log with a distinct label: middleware, guard, interceptor (one line before next.handle(), one inside a tap on the returned stream), pipe, handler, and exception filter. Then send two requests.

Successful request

The console shows:

  1. middleware
  2. guard
  3. interceptor:before
  4. pipe
  5. handler
  6. interceptor:after

If you add a second interceptor, the "before" lines print in binding order and the "after" lines print in reverse. Interceptors wrap the handler like nested function calls. The outermost interceptor starts first and finishes last. This explains why a timing interceptor bound globally measures more than one bound on the method.

Guard rejection

Make the guard return false and the trace shrinks to:

  1. middleware
  2. guard
  3. filter

No interceptor line and no pipe line appear. The guard's rejection becomes a ForbiddenException, and the exception filter handles it directly. This is why a logging interceptor never records denied requests, and why validation errors never appear for unauthorized callers.

Why this saves time

Most "my check didn't fire" bugs come down to two causes. Either the check sits in a layer the request never reached, or it runs after the step it was meant to protect. A labeled trace shows which case you have in one run. You don't have to read framework source or guess which binding scope wins. Keep the tracing components in a dev-only module so you can switch them on again whenever a new global binding changes the order.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nestjs guards vs interceptors vs middleware, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.