02 / 06

What is a guard in NestJS and when should you use one over middleware?

A guard implements CanActivate and returns a boolean to allow or block a request. Unlike middleware, guards run after routing — they know which controller and handler will process the request, enabling metadata-driven authorization decisions. Use guards for auth; use middleware for transport-level concerns that don't depend on the route.

Basic JWT auth guard
Guards vs middleware — decision guide:
  1. 1

    Guards — run after routing; know the target handler; can read @SetMetadata() via Reflector.

  2. 2

    Middleware — run before routing; cannot read route metadata; suited for request preprocessing.

  3. 3

    Use guards for: JWT verification, RBAC, API key validation, subscription checks.

  4. 4

    Use middleware for: logging, CORS, body parsing, session hydration, rate limiting.

  5. 5

    Guards can return boolean, Promise<boolean>, or Observable<boolean>.