CodePark/ questions / Middleware & request lifecycle
START PRACTICINGPRACTICE
Backend question · NestJS › Middleware & request lifecycle

When should you use middleware, a guard, an interceptor, a pipe or an exception filter? Give one typical job for each.

Each one has its own job:

  • Middleware runs before Nest knows the route details, and it has no ExecutionContext. Use it for generic request work: setting a request ID, CORS, body parsing or a raw access log.
  • A guard answers "may this request reach this handler?". It fits authentication and authorization, often driven by route metadata.
  • An interceptor wraps the handler and sees both the request and the result stream. Use it for response mapping, timing logs, caching, timeouts and serialisation.
  • A pipe works on a single handler argument. Use it to validate DTOs and convert params.
  • An exception filter decides how errors become responses. Examples: a consistent error format, or mapping domain errors to HTTP codes.
  • Middleware does generic request work and has no handler context.
  • A guard makes authentication and authorization decisions.
  • An interceptor wraps the handler for result changes, timing and caching.
  • A pipe validates and transforms handler arguments.
  • An exception filter shapes error responses.