In a NestJS e2e test, why does overrideGuard(AppAuthGuard) leave orders requests failing with 403 when that guard is registered through APP_GUARD, and how do you fix it?
answer
- the token is not the class
- a multi provider under a generated key
- alias instead of instantiate
- then override the provider
basics
~10 s{ provide: APP_GUARD, useClass: AppAuthGuard } is stored under a generated APP_GUARD token, so no override keyed by AppAuthGuard matches. Register AppAuthGuard as a provider, point APP_GUARD at it with useExisting, then call overrideProvider(AppAuthGuard).
solid answer
~40 sWhen Nest scans `{ provide: APP_GUARD, useClass: AppAuthGuard }`, it stores the guard under a generated token of the form `APP_GUARD (UUID: ...)` and adds it to the global guards. `AppAuthGuard` is never a token in the container, and it is not a decorator-bound injectable either, so `overrideGuard(AppAuthGuard)` and `overrideProvider(AppAuthGuard)` both find nothing and are silently ignored; even `overrideProvider(APP_GUARD)` misses the generated key. The real guard keeps rejecting the request by returning `false`, which Nest turns into a 403 "Forbidden resource". The documented fix is to list `AppAuthGuard` in the module's `providers` and register `{ provide: APP_GUARD, useExisting: AppAuthGuard }`. Production behaviour is unchanged, but the guard now lives under its own class token, so `overrideProvider(AppAuthGuard).useClass(...)` or `.useValue(...)` replaces it. Use `overrideProvider` here, not `overrideGuard`. The same applies to `APP_PIPE`, `APP_INTERCEPTOR` and `APP_FILTER`.
code
typescript · 13 linesimport { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { OrdersModule } from './orders/orders.module.js';
import { AppAuthGuard } from './auth/app-auth.guard.js';
@Module({
imports: [OrdersModule],
providers: [
AppAuthGuard,
{ provide: APP_GUARD, useExisting: AppAuthGuard },
],
})
export class AppModule {}go deeper
Recall that a guard registered through APP_GUARD cannot be replaced by class name unless it is aliased with useExisting.
Explain how the scanner stores APP_GUARD entries under a generated token, and why overrideGuard and overrideProvider both miss it.
Diagnose a silent override miss from a 403 in an e2e run, apply the useExisting fix with overrideProvider, and assert the stand-in is in place.
Set a team rule for registering global enhancers so they stay testable, and keep a few un-overridden tests proving the real guard is wired.
## The setup An `OrdersController` sits behind a **global guard**: a class implementing `CanActivate` that every route passes through. The usual way to register one inside the module graph, so it can use dependency injection, is the `APP_GUARD` token: ```typescript providers: [{ provide: APP_GUARD, useClass: AppAuthGuard }] ``` An e2e suite wants requests to pass without real credentials, so it chains `.overrideGuard(AppAuthGuard).useValue({ canActivate: () => true })`. Every request still returns `403` with the body `{"message":"Forbidden resource","error":"Forbidden","statusCode":403}`. ## Why nothing matched The answer is in how Nest scans enhancer tokens: 1. The scanner sees `provide: APP_GUARD` and recognises it as one of the special **application enhancer** tokens (`APP_GUARD`, `APP_PIPE`, `APP_INTERCEPTOR`, `APP_FILTER`). 2. It rewrites the registration under a **generated token**, `APP_GUARD (UUID: <uuid>)`, so several `APP_GUARD` registrations can coexist. The docs describe this as a "multi" provider. 3. After instantiation it adds that instance to the application's global guards. Now compare what the overrides search: - `overrideGuard(AppAuthGuard)` looks for `AppAuthGuard` among **injectables**, the classes bound through decorators such as `@UseGuards()`. The global guard is not there. - `overrideProvider(AppAuthGuard)` looks for a **provider** whose token is `AppAuthGuard`. The token is the generated string, not the class. - `overrideProvider(APP_GUARD)` looks for the literal `'APP_GUARD'` token, which was rewritten too. None of them finds a match, and an unmatched override is ignored without error, so the real guard runs. ## The documented fix: useExisting Change the registration so the class itself becomes an ordinary provider and the enhancer slot merely **aliases** it: | Registration | Who creates the guard | Overridable by class token | |---|---|---| | `{ provide: APP_GUARD, useClass: AppAuthGuard }` | Nest, behind the generated token | no | | `AppAuthGuard` plus `{ provide: APP_GUARD, useExisting: AppAuthGuard }` | Nest, as the `AppAuthGuard` provider | yes, with `overrideProvider(AppAuthGuard)` | In production nothing changes: the same class runs on every route. In the test, `.overrideProvider(AppAuthGuard).useClass(AllowAllGuard)` (or `.useValue(...)`) replaces the provider, and the `APP_GUARD` alias resolves to the replacement, so every request goes through the stand-in. Note which method: since the guard now exists as a provider, **`overrideProvider`** is the one that matches. `overrideGuard(AppAuthGuard)` still searches injectables and still misses. ## Other ways a global guard appears - **`app.useGlobalGuards(new AppAuthGuard())` in `main.ts`**: this guard is not part of the module graph at all, and since the e2e test never runs `main.ts`, it is simply absent from the test app. That makes the test pass while hiding the fact that the guard is not tested. - **`@UseGuards(AppAuthGuard)` on the controller**: here `overrideGuard(AppAuthGuard)` is the correct call. ## Choosing what the stand-in does - A guard that **always returns `true`** tests routing, pipes and handlers but no access rules. - A stand-in that **sets a known user on the request** before returning `true` lets handlers that read the current user behave realistically. - Keeping a few tests **without the override**, sending real or deliberately bad credentials, proves the global guard is actually wired; an override-only suite would stay green if someone deleted the `APP_GUARD` registration. ## Verifying the fix Because an unmatched override is silent, prove the fix rather than trusting a green run: 1. Before the change, run one request and confirm the 403 with the "Forbidden resource" body. 2. Switch the registration to `useExisting` and the test to `overrideProvider(AppAuthGuard)`. 3. Assert `moduleRef.get(AppAuthGuard)` returns your stand-in (the same object, for a `useValue` override). 4. Run the request again and expect 200. 5. Keep one suite without the override that still expects 403 for a request with no credentials. ## Checklist - Register the guard class in `providers` and alias it with `useExisting`. - Override it with `overrideProvider`, not `overrideGuard`. - Assert `moduleRef.get(AppAuthGuard)` is the stand-in, to catch a silent miss. - Apply the same pattern to `APP_PIPE`, `APP_INTERCEPTOR` and `APP_FILTER` registrations you need to replace.
- In NestJS, why does an e2e test pass when the global guard is registered with app.useGlobalGuards() in main.ts?`useGlobalGuards()` configures the application instance that `main.ts` creates; it is not part of the module graph. The e2e test builds its own instance from the testing module and never runs `main.ts`, so that guard simply is not there. The suite passes without testing access control at all, which is a reason to register global guards through `APP_GUARD` instead.
- After switching to useExisting, why keep a few NestJS e2e tests that do not override the global guard?An override-only suite stays green even if someone removes the `APP_GUARD` registration, because every test replaced the guard anyway. A handful of tests that send no credentials and expect 403, or valid ones and expect 200, prove the real guard is wired globally while the rest of the suite keeps the stand-in for speed.
- overrideGuard() replaces a guard wherever it is registered, including APP_GUARD
- overrideProvider(APP_GUARD) swaps every global guard at once
- An override that matches nothing makes compile() fail loudly
- Switching APP_GUARD to useExisting changes how the guard behaves in production
- A guard added with useGlobalGuards() in main.ts is active in e2e tests