In a NestJS 12 app, a guard registered through APP_GUARD and one passed to app.useGlobalGuards() are both global; which runs first, and why?
answer
- two ways to reach one list
- bootstrap time versus main.ts
- append, never prepend
- request scope goes to the back
basics
~10 sA singleton APP_GUARD guard runs first: Nest adds APP_GUARD providers while NestFactory.create() builds the module graph, and app.useGlobalGuards() later appends. A request-scoped APP_GUARD guard runs after all singleton global guards instead.
solid answer
~40 sBoth registrations land in the application's global guard list, which runs before any controller or route guard. `APP_GUARD` providers are applied during `NestFactory.create()`, while the module graph is scanned and instantiated, and each one is appended in registration order. `app.useGlobalGuards()` can only be called on the app that `create()` returned, and it appends too, so its guards come after every singleton `APP_GUARD` guard. The exception is an `APP_GUARD` whose class is request-scoped or transient: Nest keeps it in a separate list that is appended after the static global guards, so it runs after the `useGlobalGuards()` guard. The other difference is injection: a guard built with `new` for `useGlobalGuards()` is created outside any module and cannot inject dependencies, while an `APP_GUARD` provider can.
code
typescript · 13 lines// app.module.ts
@Module({
providers: [
{ provide: APP_GUARD, useClass: SessionGuard }, // singleton: runs 1st
{ provide: APP_GUARD, useClass: TenantScopeGuard }, // @Injectable({ scope: Scope.REQUEST }): runs 3rd
],
})
export class AppModule {}
// main.ts
const app = await NestFactory.create(AppModule); // APP_GUARD providers applied here
app.useGlobalGuards(new MaintenanceGuard()); // appended afterwards: runs 2nd
await app.listen(3000);go deeper
Know both ways to make a guard global, useGlobalGuards() and an APP_GUARD provider, and that global guards run before controller and route guards.
Explain that only APP_GUARD guards get dependency injection, because a useGlobalGuards() guard is built with new outside any module.
Predict the run order from bootstrap: APP_GUARD singletons applied during NestFactory.create(), useGlobalGuards() appended after, request-scoped APP_GUARD guards appended per request.
Pick one registration style for global guards and keep them in one module, so the order a security review sees is the order that runs.
## Two doors into one global list A **NestJS** guard is **globally bound** when it is registered in either of two ways: - **`app.useGlobalGuards(new SomeGuard())`** in `main.ts`, on the application instance. - **An `APP_GUARD` provider** in any module: `{ provide: APP_GUARD, useClass: SomeGuard }`. Either way the guard runs for every route, **before** every controller-level and route-level guard. The request-lifecycle docs treat both as "global". What they do not spell out is the order **between** the two kinds, which the source and a running app settle. ## Why APP_GUARD usually comes first The v12.1.2 bootstrap sequence explains it: 1. `NestFactory.create(AppModule)` scans the module graph, instantiates the providers, and then **applies the application providers**: every `APP_GUARD` (and `APP_INTERCEPTOR`, `APP_PIPE`, `APP_FILTER`) found during the scan is pushed onto the matching global list. 2. `create()` returns the application, and only then can `main.ts` call `app.useGlobalGuards()`, which **appends** its guards to the same list. 3. Routes are registered on `app.init()` (which `app.listen()` calls), reading that list. So for singleton guards the list is: every `APP_GUARD` guard in registration order, then every `useGlobalGuards()` guard in the order passed. The docs add that `APP_GUARD` may be registered several times, in the same or different modules, and every registered guard runs, **in registration order**. ## The request-scoped exception An `APP_GUARD` whose class is **request-scoped** (or transient) cannot be created once at bootstrap. Nest keeps a reference to it in a **separate list** and, for each request, appends the resolved instances **after** all the static global guards. A running app shows the effect: | Registered as | Scope | Runs | |---|---|---| | `APP_GUARD` | singleton | 1st | | `app.useGlobalGuards()` | an instance, created with `new` | 2nd | | `APP_GUARD` | `Scope.REQUEST` | 3rd | | `@UseGuards()` on the controller | any | 4th | A request-scoped `APP_GUARD` therefore runs after a `useGlobalGuards()` guard, even if the module providing it was scanned first. ## The injection difference The order is the subtle part; the documented reason teams choose `APP_GUARD` is **dependency injection**: - A guard passed to `useGlobalGuards()` is constructed by you, outside the context of any module, so it **cannot inject dependencies** such as a `Reflector` or a configuration service unless you pass them in by hand. - An `APP_GUARD` provider is created by Nest's injector inside the module that declares it, so its constructor dependencies resolve like any provider's. - `APP_GUARD`, like the other `APP_*` tokens, is a **pseudo-provider** consumed during bootstrap: it cannot be retrieved later with `app.get()` or injected elsewhere. ## The same mechanism for the other APP_* tokens `APP_INTERCEPTOR`, `APP_PIPE` and `APP_FILTER` are applied in the same bootstrap step, and `useGlobalInterceptors()`, `useGlobalPipes()` and `useGlobalFilters()` append in the same way. What that means differs by component: | Component | Effect of the shared list order | |---|---| | Interceptors | the `APP_INTERCEPTOR` one runs its inbound code first and its outbound code last | | Pipes | the `APP_PIPE` one transforms each argument first | | Filters | the list is reversed, so the `useGlobalFilters()` one is checked first | So two global catch-everything filters, one per style, do not both run: the one passed to `useGlobalFilters()` answers. ## How to check it in your own app - Log a line from each global guard's `canActivate()` and send one request: the printed order is the effective order. - Look for `APP_GUARD` classes decorated `@Injectable({ scope: Scope.REQUEST })` or `Scope.TRANSIENT`: those run after every singleton global guard. - Search `main.ts` for `useGlobalGuards()` calls and every module for `APP_GUARD`; a mix of both is the usual source of surprise. ## What to do with this - If one global guard must run before another, for example a cheap maintenance switch before an expensive token check, **do not mix registration styles and hope**. Register both the same way and control their order explicitly. - Prefer one style per codebase. `APP_GUARD` gives injection; keeping every global guard in one module keeps the registration order readable. - Remember the request-scoped case: making a global guard request-scoped silently moves it behind the singleton global guards.
- In a NestJS 12 app, can you retrieve an APP_GUARD guard with app.get() to inspect it?No. `APP_GUARD`, like the other `APP_*` tokens, is a pseudo-provider that Nest consumes during bootstrap; it cannot be retrieved later with `app.get()` or injected elsewhere. If other code needs the guard instance, register the class as an ordinary provider too and point the `APP_GUARD` entry at it with `useExisting`.
- In a NestJS 12 app, two feature modules each register an APP_GUARD; what decides which runs first?Registration order: the docs say every registered `APP_GUARD` runs for each request in the order it was registered, in effect the order in which Nest scans the modules. Because that order is implicit, a team that needs a fixed sequence keeps its global guards in one module.
- useGlobalGuards() guards run first because main.ts code takes priority.
- APP_GUARD guards run after controller guards because they are module providers.
- A request-scoped APP_GUARD keeps its place among the singleton global guards.
- A guard passed to useGlobalGuards() can inject services through its constructor.