skip to content

In a NestJS app, how do you register a JwtAuthGuard extending AuthGuard('jwt') globally and still let routes marked @Public() through?

level: middleimportance: must knowfreq 62%

answer

  1. closed by default, opened explicitly
  2. a pseudo-provider token from core
  3. metadata flag set by a decorator
  4. override canActivate, then super
  5. handler first, then class

basics

~10 s

Provide the guard under the APP_GUARD token, mark open routes with a @Public() decorator built on SetMetadata, and override canActivate() to read that flag with Reflector, returning true before calling super.canActivate().

solid answer

~30 s

Add `{ provide: APP_GUARD, useClass: JwtAuthGuard }` to a module's providers; the guard then covers every route, and because the container builds it, it can inject `Reflector`. Define `Public = () => SetMetadata(IS_PUBLIC_KEY, true)`. In `JwtAuthGuard extends AuthGuard('jwt')`, override `canActivate()`: if `reflector.getAllAndOverride(IS_PUBLIC_KEY, [context.getHandler(), context.getClass()])` is true, return `true`; otherwise return `super.canActivate(context)`, which runs Passport. Two consequences: the login route needs `@Public()` too, because global guards run before its route-level `LocalAuthGuard`; and on a public route Passport never runs, so `req.user` is undefined.

code

typescript · 29 lines
typescript
import { ExecutionContext, Injectable, Module, SetMetadata } from '@nestjs/common';
import { APP_GUARD, Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }
    return super.canActivate(context);
  }
}

@Module({
  providers: [{ provide: APP_GUARD, useClass: JwtAuthGuard }],
})
export class AuthModule {}

go deeper

for a junior

Remember the three parts: APP_GUARD to bind the guard everywhere, a @Public() decorator made with SetMetadata, and a guard that checks it.

for a middle

Explain why the override reads both handler and class metadata, why the login route needs @Public(), and why APP_GUARD beats useGlobalGuards for injection.

for a senior

Show you have debugged the fallout: login returning 401, public routes with no req.user, a class-level flag ignored, and a guard returning false giving 403.

for a principal

Argue for deny-by-default as a team convention, how to review new public routes, and how to keep the public list small and auditable.

## Why protect everything by default In an API where most routes need a signed-in caller, putting `@UseGuards(JwtAuthGuard)` on every controller is a list someone will eventually forget to extend. The NestJS Passport recipe flips the default: bind the JWT guard **globally**, so every route is closed, and mark the few open routes (login, a health check, a public catalogue) explicitly. A forgotten decorator then fails closed, with a 401, instead of failing open. It also makes review easier: the list of open routes is exactly the list of `@Public()` usages, which a search can produce, rather than the much longer list of routes that happen to lack a guard. ## The three pieces 1. **Register the guard globally through DI.** In any module's `providers`, add `{ provide: APP_GUARD, useClass: JwtAuthGuard }`, with `APP_GUARD` imported from `@nestjs/core`. The guard becomes global regardless of which module declares it, and because the container creates it, its constructor can receive `Reflector`. 2. **Create the flag.** `export const IS_PUBLIC_KEY = 'isPublic'` and `export const Public = () => SetMetadata(IS_PUBLIC_KEY, true)`. `SetMetadata` only attaches metadata to the method or class it decorates; on its own it changes nothing. 3. **Teach the guard to read it.** `JwtAuthGuard extends AuthGuard('jwt')`, injects `Reflector` (calling `super()` in its constructor) and overrides `canActivate()`: read the flag with `this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [context.getHandler(), context.getClass()])`; if it is `true`, return `true`; otherwise return `super.canActivate(context)`, which runs Passport. ## Ways to bind the guard | Binding | Scope | Can it receive `Reflector` by injection? | |---|---|---| | `{ provide: APP_GUARD, useClass: JwtAuthGuard }` | every route in the app | yes, the container builds it | | `app.useGlobalGuards(new JwtAuthGuard(...))` | every route in the app | no, you construct it yourself outside any module | | `@UseGuards(JwtAuthGuard)` | one controller or one handler | yes | ## The login route is the classic trap Guards run **global first, then controller, then route**. The login handler carries `@UseGuards(LocalAuthGuard)`, but the global JWT guard runs before it, sees no bearer token and throws a 401 before the username and password are ever checked. With the flag in place, a login request flows like this: 1. The global `JwtAuthGuard` reads `@Public()` on the handler and returns `true` without running Passport. 2. The route-level `LocalAuthGuard` runs passport-local, whose `validate()` checks the username and password and returns the user. 3. The handler receives `req.user` and signs a token for it. The fix is to put `@Public()` on the login route as well: the global guard steps aside, and the route-level `LocalAuthGuard` still runs and still rejects bad credentials. `@Public()` only switches off the global JWT check; it does not switch off other guards bound to that route. ## What a public route gives up - With the recipe's override, a public route returns before `super.canActivate()` is called, so Passport never runs and **`req.user` is undefined**, even when the client sent a valid token. - If a public route should still recognise a signed-in caller (a catalogue that shows prices to members), let it attempt authentication and tolerate failure, for example by overriding `handleRequest()` to return `null` instead of throwing when the route is public. - A `@Public()` on a controller class opens every handler in it, because `getAllAndOverride` checks the handler first and then the class, returning the first value that is defined. ## Mistakes worth naming - Reading the flag with `reflector.get(IS_PUBLIC_KEY, context.getHandler())` only: a `@Public()` placed on the controller class is ignored. - Returning `false` for public routes: a guard returning `false` produces a 403, the opposite of what was intended. - Expecting `APP_GUARD` to be limited to its own module: it applies to every route. - Assuming `@Public()` also switches off route-level guards such as the login route's `LocalAuthGuard`: it only affects guards that read the flag. - Registering the guard with `useGlobalGuards(new JwtAuthGuard())` and then finding `this.reflector` undefined. Where several guards are bound globally, they run in registration order; how a role or policy guard is layered after this one, and why it must come second, is covered with role and policy guards. The `Reflector` API in general, including `createDecorator`, is covered with guards and interceptors.

  • A public route wants req.user when a valid token happens to be present. How?
    Do not return early. Run `super.canActivate(context)` for public routes too and override `handleRequest(err, user, info, context)` so that, when the route is public, it returns `user` or `null` instead of throwing. The guard then sets `req.user` to the user or to `null` and lets the request through.
  • Why not register it with app.useGlobalGuards(new JwtAuthGuard())?
    `useGlobalGuards()` registers an instance created outside any module, so the container cannot inject `Reflector` or `AuthModuleOptions` into it; you would have to construct and pass them yourself. `APP_GUARD` lets DI build the guard and keeps the registration inside a module.
  • Why getAllAndOverride rather than reflector.get on the handler?
    `reflector.get(IS_PUBLIC_KEY, context.getHandler())` sees only the method, so `@Public()` on a whole controller is ignored. `getAllAndOverride` checks each target in the order given, handler then class, and returns the first defined value, so both placements work and the handler's value wins.

Picture an office where every door locks by default. The guard at each door first looks for an 'open to visitors' sign on that door or on the whole corridor, and asks for a badge only when there is none. The sign does nothing by itself; it works only because the guard was told to read it.

  • A guard provided with APP_GUARD only covers controllers in that same module
  • A route-level LocalAuthGuard on the login route runs before the global JWT guard
  • The @Public() decorator disables the global guard without any code in the guard
  • A public route should make canActivate() return false so Passport is skipped
  • With the recipe's guard, a public route still fills req.user when a token is sent