Why would every route behind AuthGuard('jwt') in a NestJS app return 500 and log Unknown authentication strategy "jwt" after a refactor?
answer
- registration is a side effect
- constructor calls passport.use
- lookup by name per request
- scope bubbles up the chain
basics
~20 sPassport has no strategy registered as 'jwt' because the JwtStrategy instance was never created: it left the providers, its module is not imported, it was renamed, or it became request-scoped. Passport's plain Error reaches Nest as a 500.
solid answer
~40 s`PassportStrategy(Strategy, name?)` registers the strategy with Passport's global instance inside its constructor, under the second argument or the package's default name, `'jwt'` for passport-jwt. `AuthGuard('jwt')` looks that name up on each request; when it is missing, Passport passes `new Error('Unknown authentication strategy "jwt"')` to `next`, the guard rejects with that plain `Error`, and Nest's default filter answers 500 and logs it. Nothing fails at startup. The usual causes are a `JwtStrategy` dropped from `providers` or a module no longer imported, a rename such as `PassportStrategy(Strategy, 'jwt-access')`, or a request-scoped dependency: request scope bubbles up, and Nest never instantiates a request-scoped strategy. Keep strategies singletons and resolve request-scoped services with `ModuleRef` inside `validate()`.
code
typescript · 23 linesimport { Injectable } from '@nestjs/common';
import { ContextIdFactory, ModuleRef } from '@nestjs/core';
import { PassportStrategy } from '@nestjs/passport';
import type { Request } from 'express';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UsersService } from './users.service.js';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private moduleRef: ModuleRef) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET as string,
passReqToCallback: true,
});
}
async validate(request: Request, payload: { sub: string }) {
const contextId = ContextIdFactory.getByRequest(request);
const users = await this.moduleRef.resolve(UsersService, contextId);
return users.findOne(payload.sub);
}
}go deeper
Remember that a strategy class must be listed in a module's providers, and that the name in AuthGuard() must match the strategy's name.
Explain that PassportStrategy registers with Passport inside its constructor, so registration depends on Nest instantiating the provider.
Trace the 500 from Passport's next(err) through the guard to the default filter, and spot a request-scoped dependency that silently stops instantiation.
Set conventions that prevent this class of break: named strategy constants, guard classes instead of strings, and a boot test of one guarded route.
## How a strategy becomes known to Passport Passport keeps a **name-to-strategy table** on one global instance. In plain Passport you fill it with `passport.use(...)`. In NestJS you never call that yourself: the constructor generated by `PassportStrategy(Strategy, name?)` does it. When the container instantiates your `JwtStrategy`, the mixin calls `passport.use()` with: - the **second argument** to `PassportStrategy()`, if you passed one (`PassportStrategy(Strategy, 'jwt-access')`), or - the strategy package's **default name**, which is `'jwt'` for passport-jwt and `'local'` for passport-local. So the strategy is registered **as a side effect of DI creating the provider**. If Nest never creates it, Passport never hears of it. Registering a second strategy under a name that is already taken replaces the first one in the table. ## What happens at request time 1. `AuthGuard('jwt')` calls `passport.authenticate('jwt', ...)`. 2. Passport looks `'jwt'` up in its table. 3. If the name is missing, Passport passes `new Error('Unknown authentication strategy "jwt"')` to its `next` callback. 4. The guard's promise rejects with that plain `Error`. 5. It is not an `HttpException`, so Nest's default exception filter answers `{"statusCode":500,"message":"Internal server error"}` and logs the error. The same lookup happens for every name in a chain such as `AuthGuard(['jwt', 'api-key'])`: Passport tries the strategies in order, and the first unregistered name it reaches produces this error, even if an earlier strategy merely failed. Nothing fails at bootstrap. `AuthGuard` only optionally injects `AuthModuleOptions`, and the strategy name is a string looked up per request, so the app starts cleanly and breaks on the first guarded call. ## Likely causes after a refactor | Cause | Why the strategy is missing | |---|---| | `JwtStrategy` dropped from `providers` | the class is never instantiated | | its module no longer imported into the app graph | Nest never loads that module's providers | | renamed with `PassportStrategy(Strategy, 'jwt-access')` | it registers under the new name; `'jwt'` stays empty | | injects a request-scoped provider | request scope bubbles up, and Nest never instantiates a request-scoped strategy | | declared with `scope: Scope.REQUEST` | the same: the recipe says Nest never instantiates it | The request-scope case is the subtle one. The NestJS docs state that request scope **bubbles up the injection chain**: if your strategy's constructor injects a service that is request-scoped, the strategy becomes request-scoped too. Request-scoped providers are created per request for routes that need them, but a strategy is not tied to any route, so Nest never creates it, and `passport.use()` never runs. ## Diagnosing it 1. Read the logged message: the quoted name tells you which lookup failed. 2. Search for `PassportStrategy(` and check each second argument against the names used in `AuthGuard(...)`. 3. Confirm the strategy class appears in a module's `providers`, and that module is reachable from the root module's `imports`. 4. Put a log line in the strategy's constructor; if it never prints at startup, the provider is not being built. 5. Check the strategy's constructor parameters for anything request-scoped, directly or through its own dependencies. ## Fixes and prevention - Provide each strategy exactly once, in the module that owns authentication, and import that module where the app is assembled. - Replace magic strings with guard classes such as `JwtAuthGuard extends AuthGuard('jwt')`, and keep the strategy's name in a shared constant. - Keep strategies singletons. When a request-scoped service is needed, set `passReqToCallback: true`, build a context with `ContextIdFactory.getByRequest(request)` and fetch the service with `moduleRef.resolve(Service, contextId)` inside `validate()`. - Give every distinct strategy its own name (`'jwt-access'`, `'jwt-refresh'`) so one registration cannot silently replace another. - Keep one test that boots the real module graph and calls a guarded route, so a missing strategy fails a build rather than production. How to write that kind of test, and how module imports and provider scopes work in general, are covered with NestJS testing and with the module and provider lessons; this question is about the Passport binding failing.
- Why does the app start without any error?`AuthGuard('jwt')` has no required dependencies (its options are injected as optional), and the strategy name is only a string looked up when a request arrives. A provider that nothing lists is simply never built, so there is nothing for the container to complain about at bootstrap.
- Can two strategies both use passport-jwt's Strategy class?Yes, if each gets its own name: `PassportStrategy(Strategy, 'jwt-access')` and `PassportStrategy(Strategy, 'jwt-refresh')`, guarded by `AuthGuard('jwt-access')` and `AuthGuard('jwt-refresh')`. Left unnamed, both register as `'jwt'` and the one instantiated later replaces the other in Passport's table, which typically shows up as unexpected 401s rather than a 500.
- AuthGuard('jwt') finds the strategy by scanning the module for a JwtStrategy class
- A missing strategy makes Nest fail at bootstrap with a dependency error
- Marking the strategy Scope.REQUEST gives each request its own registered strategy
- Importing PassportModule is enough to register every strategy class in the project
- Unknown authentication strategy means the token was signed with the wrong algorithm