In a NestJS 12 app, why must the authentication guard run before a roles or policy guard, and what decides which global guard runs first?
answer
- who before may
- request.user is the handoff
- global, controller, route
- module-scan order for APP_GUARD
- useGlobalGuards comes later
basics
~20 sRole and policy guards read the user that authentication puts on request.user, so run first they see nobody. Global guards precede controller and route guards; singleton APP_GUARD providers run in module-scan order, before app.useGlobalGuards() ones.
solid answer
~40 sIn NestJS 12 the authentication guard sets `request.user` and the authorization guard reads it, so authorization run first sees nobody: the docs' plain roles guard throws a `TypeError` and the caller gets a 500, a defensive one returns 403 to everyone, and `@nestjs/authorization`'s guard treats every caller as a guest, so signed-in staff get 401. Order is global, then controller, then route guards; among global guards, singleton `APP_GUARD` providers run in the order Nest scans their modules, then `app.useGlobalGuards()` guards, then request-scoped `APP_GUARD` ones. So `AuthenticationModule` must be imported before `AuthorizationModule`, which refuses to start when `AuthenticationGuard` comes second. A Passport `AuthGuard()` subclass in the wrong order is only logged, and one added with `useGlobalGuards()` always runs after, so register it as an `APP_GUARD`.
code
typescript · 24 linesimport { Module } from '@nestjs/common';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { AuthModule } from './auth/auth.module.js';
@Module({
imports: [
// Scanned first: its global guard sets request.user.
AuthenticationModule.forRootAsync({
useFactory: () => ({
accessToken: {
key: process.env.JWT_SECRET!,
issuer: 'https://api.example.com',
audience: 'orders-api',
ttl: '15m',
},
}),
}),
// Its global guard reads request.user, so it must come second.
AuthorizationModule.forRoot(),
AuthModule,
],
})
export class AppModule {}go deeper
Remember the handoff: authentication puts the user on request.user, and roles or policy guards read it, so authentication must run first.
Explain the global, controller, route order and how global guards are ordered among themselves, including why app.useGlobalGuards() guards run after singleton APP_GUARD providers.
Diagnose the symptoms of a wrong order (500, blanket 403, 401 for signed-in staff) and explain what the authorization package's startup check catches and what it only logs.
Set the team convention: one singleton global authentication guard registered ahead of authorization, plus an end-to-end test that proves the order on every service.
## What each guard needs from the other Authentication answers *who is calling*; authorization answers *may they do this*. In a NestJS app both are usually guards, and they share one handoff: the authentication guard verifies the credential and puts the user on `request.user`, and a roles guard or a policy guard reads `request.user` and decides. The authorization guard cannot do its work until the authentication guard has done its own, so their order is a correctness requirement, not a style choice. The dependency runs one way only. Authentication never needs authorization's result, and an authorization guard should never re-verify the credential itself: if it did, two components would parse tokens, and they would eventually disagree about who the caller is. ## The order Nest runs guards in Guards run after middleware and before interceptors and pipes. Among guards: 1. **Global** guards run first, then **controller** guards (`@UseGuards()` on the class), then **route** guards (`@UseGuards()` on the method). 2. Within one `@UseGuards(A, B)`, they run in the order listed. 3. Among global guards, in the order Nest registers them: - singleton `APP_GUARD` providers, in the order Nest scans the modules that declare them; for two modules imported side by side, that follows the order of the `imports` array; - then guards added with `app.useGlobalGuards()` in `main.ts`; - then request-scoped or transient `APP_GUARD` providers. | Registration | Runs | |---|---| | `{ provide: APP_GUARD, useClass: ... }`, singleton | first among guards, in module-scan order | | `app.useGlobalGuards(...)` | after the singleton `APP_GUARD` guards | | `APP_GUARD` with request or transient scope | after both of the above | | `@UseGuards()` on a controller, then on a method | after every global guard | A consequence people miss: an authentication guard bound per controller with `@UseGuards()` always runs *after* a global authorization guard. ## What goes wrong in the wrong order The symptom depends on how the authorization guard treats a missing user: | Authorization guard | Symptom when it runs before authentication | |---|---| | The docs' plain roles guard, which reads `user.roles` | a `TypeError` on `undefined`, so a 500 | | A roles guard written with optional chaining | every caller denied with a 403 | | `@nestjs/authorization`'s `AuthorizationGuard` | every caller seen as a guest, so a signed-in staff member gets a 401 on a staff-only route | None of these reads like an ordering bug at first glance, which is why interviewers ask about it. ## How the first-party authorization package checks the order The NestJS 12 docs teach `@nestjs/authentication` and `@nestjs/authorization` as a pair, and each registers a global guard. The docs state the rule directly: Nest runs global guards in the order it scans modules, so `AuthenticationModule` has to be imported before `AuthorizationModule`. The authorization module verifies this at startup: - It recognises `@nestjs/authentication`'s `AuthenticationGuard` by a marker the guard class carries. When that guard would run after the authorization guard, the **app refuses to start**, with an error naming both guards and the fix. - Other authentication guards, such as a subclass of Passport's `AuthGuard()`, carry no marker, so the check can only go by class name. In the wrong order it **logs an error and the app starts**. - A guard added with `app.useGlobalGuards()` cannot be seen by the check, and it runs after every singleton `APP_GUARD`, so it always comes after the authorization guard. The docs say to register authentication as a singleton `APP_GUARD` instead. - If you authenticate per controller with `@UseGuards()`, pass `globalGuard: false` to `AuthorizationModule.forRoot()` and list `AuthorizationGuard` after your authentication guard in the same `@UseGuards()`. ## Getting it right - Register authentication as a global singleton guard, in a module scanned before the authorization guard's. - Keep the authorization guard from authenticating: a roles or policy guard that re-parses the token duplicates the authentication guard and drifts from it. - Keep an end-to-end test that signs in and calls a protected route; it catches the Passport case, where the startup check only logs. - Prefer one global authentication guard with explicit opt-outs for open routes over authentication bound per controller: per-controller binding is exactly the case where a global authorization guard runs first. - Remember that a guest reaching a policy is legitimate on routes where authentication is optional. The guard order decides whether a *signed-in* caller is wrongly seen as one.
- Why does the docs' plain RolesGuard return a 500 rather than a 403 when it runs before authentication?It reads `request.user` and then `user.roles`. With no authentication yet, `user` is `undefined`, so the property access throws a `TypeError`. That is not an `HttpException`, so Nest's built-in exception handling answers with a 500 Internal server error. A 403 would only come from the guard returning `false`, which it never reaches.
- You authenticate per controller with @UseGuards(JwtAuthGuard); how do you keep @nestjs/authorization's guard after it?Global guards run before controller guards, so the default global `AuthorizationGuard` would run first. Pass `globalGuard: false` to `AuthorizationModule.forRoot()` and bind both in order on each controller: `@UseGuards(JwtAuthGuard, AuthorizationGuard)`. Guards in one `@UseGuards()` run in the order listed. The startup check logs an error for any `@Can()` that no guard enforces.
- Does importing AuthenticationModule first also protect a request-scoped authentication guard?No. A request-scoped or transient `APP_GUARD` runs after every singleton global guard, and after `app.useGlobalGuards()` ones, whatever the import order. The NestJS 12 authorization docs list it among the registrations that always run after the authorization guard. Register authentication as a singleton `APP_GUARD`.
A concert venue: the ticket desk at the entrance hands out wristbands, and the steward at the backstage door admits only the right colour. Put the steward on the street before the ticket desk and every fan arrives with no wristband: not refused for the wrong colour, just unknown.
- Controller-level guards run before global guards, so binding auth per controller fixes the order.
- Guards added with app.useGlobalGuards() run before every APP_GUARD provider.
- When authorization runs first, a signed-in user simply gets a 403.
- The authorization package reorders the global guards when it finds them in the wrong order.
- The startup check refuses to boot for any misordered Passport guard.
Assumes NestJS 12; the startup order check belongs to the first-party authorization package taught by the v12 security docs.