With @nestjs/jwt in a NestJS app, how do JwtModule.register() and registerAsync() differ, and where does JwtService.sign() get its secret and expiry?
answer
- static object versus factory
- inject the config service
- module defaults, call overrides
- provider beats static secret
- async provider needs signAsync
basics
~20 sregister() takes a fixed options object; registerAsync() builds it in a factory that can inject ConfigService. JwtService.sign() merges the module's signOptions, such as expiresIn, with per-call options and uses the module secret unless the call overrides it.
solid answer
~40 s`JwtModule.register()` stores a literal options object, read as the module file loads; `registerAsync({ imports, inject, useFactory })` (or `useClass` / `useExisting`) resolves options during bootstrap, so a secret can come from `ConfigService.getOrThrow()`. `JwtService.sign(payload, options?)` starts from the module's `signOptions` and lets per-call options override them; the key comes from `secretOrKeyProvider` if one is set, otherwise the call's `secret`, the module's `secret`, then `privateKey`. With an async key provider, `sign()` and `verify()` throw `WrongSecretProviderError`, so use `signAsync()` and `verifyAsync()`. `global: true` exposes `JwtService` everywhere. In the Passport recipe the strategy verifies tokens with its own `secretOrKey`, so it must read the same secret.
code
typescript · 37 linesimport { Injectable, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule, PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.getOrThrow<string>('JWT_SECRET'),
});
}
validate(payload: { sub: string }) {
return { userId: payload.sub };
}
}
@Module({
imports: [
ConfigModule,
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.getOrThrow<string>('JWT_SECRET'),
signOptions: { expiresIn: '15m' },
}),
}),
],
providers: [JwtStrategy],
})
export class AuthModule {}go deeper
Know that JwtModule is configured with a secret and signOptions, and that JwtService.sign() turns a payload object into a token.
Explain register() versus registerAsync() timing, how sign() merges module and call options, and why the Passport strategy needs the secret separately.
Diagnose undefined secrets loaded too early, WrongSecretProviderError from an async key provider, and login working while every guarded route answers 401.
Decide where signing keys come from and who may sign, and make the signer and every verifier read one source of truth.
## What `@nestjs/jwt` gives you `@nestjs/jwt` is a thin Nest wrapper over a JSON Web Token library. `JwtModule` provides and exports one service, **`JwtService`**, with `sign()`, `signAsync()`, `verify()`, `verifyAsync()` and `decode()`. The module's options (`secret`, `publicKey`, `privateKey`, `secretOrKeyProvider`, `signOptions`, `verifyOptions`, `global`) become defaults that every call on the service starts from. In the Passport recipe, `JwtService.sign()` issues the token at login; it plays no part in checking tokens on guarded routes. ## `register()` versus `registerAsync()` | | `JwtModule.register(options)` | `JwtModule.registerAsync({...})` | |---|---|---| | Input | a plain options object | `useFactory` with `inject`, or `useClass`, or `useExisting` | | When values are read | when the decorator expression is evaluated, as the module file loads | when the container resolves the options provider during bootstrap | | Can use other providers | no | yes, for example `ConfigService` | | Extra keys | `global` | `imports`, `inject`, `global`, `extraProviders` | The practical difference is **timing and injection**. `JwtModule.register({ secret: process.env.JWT_SECRET })` reads the environment as the file loads, which can be before `@nestjs/config` has loaded a `.env` file, so the secret can end up undefined, and the failure shows only when the first token is signed. With `registerAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config) => ({ secret: config.getOrThrow('JWT_SECRET'), signOptions: { expiresIn: '15m' } }) })` the factory runs after configuration is available, and `getOrThrow` fails bootstrap loudly if the value is missing. The other two `registerAsync()` forms suit larger apps. `useClass: JwtConfigService` makes `JwtModule` instantiate a class implementing `JwtOptionsFactory` and call its `createJwtOptions()`; `useExisting` reuses a provider already available from an imported module instead of creating a second instance. Setting `global: true` makes `JwtService` injectable in every module without importing `JwtModule` again. ## How `sign()` resolves its options 1. **Options are merged.** The module's `signOptions` are the base; options passed to the call (`expiresIn`, `audience`, and so on) override them key by key. A call with `{ expiresIn: '1h' }` beats a module default of `'15m'`. 2. **The key is chosen.** If `secretOrKeyProvider` is configured it is always used. Otherwise the service takes the call's `secret`, then the module's `secret`, then the `privateKey` (call first, then module). `verify()` mirrors this with `publicKey`. 3. **String payloads are restricted.** Signing a string payload while any sign option other than `secret` or `privateKey` is in effect (including a module-level `expiresIn`) throws an error naming the offending options. Sign an object instead. ## Synchronous and asynchronous key providers `secretOrKeyProvider` may return a key or a promise of one, which is how keys are fetched from a secret store or rotated at runtime. With an **async** provider, the synchronous `sign()` and `verify()` cannot wait: they log a warning telling you to use the async variant and throw `WrongSecretProviderError`. Use `signAsync()` and `verifyAsync()` whenever the provider can be asynchronous. ## Keeping the signer and the strategy in step The recipe uses two packages that never talk to each other: - **`JwtService`** (from `@nestjs/jwt`) **signs** the token at login, with the module's `secret` and `signOptions`. - **passport-jwt's strategy** **verifies** the token on every guarded route, with the `secretOrKey` (and any `issuer`, `audience` or `algorithms`) passed to `super()` in your `JwtStrategy`. Nothing copies settings from one to the other. `JwtModule`'s `verifyOptions` affect only `JwtService.verify()`; they do not change what `AuthGuard('jwt')` accepts. So both sides must read the key from the same place, typically by injecting `ConfigService` into the strategy's constructor and passing the value to `super()`. If the two drift apart, login succeeds and every guarded call answers 401. Expiry is the one setting that crosses the boundary through the token itself: `JwtService.sign()` writes the `exp` claim from `expiresIn`, and the passport-jwt strategy rejects the token after that time because its `ignoreExpiration` option is `false` unless you set it. Shortening `signOptions.expiresIn` therefore needs no change to the strategy. ## Pitfalls - Using `register()` with values from `process.env` that a `.env` loader has not populated yet. - Expecting module `verifyOptions` to change the Passport strategy's checks. - Calling `sign()` with an async `secretOrKeyProvider` configured. - Signing a plain string while the module sets `signOptions.expiresIn`. - Adding `JwtService` to a feature module's `providers` instead of importing `JwtModule`, which creates an instance with no module options. Which claims a verifier must check, and how keys are rotated and published, are framework-neutral questions covered in the token validation and key management lessons; this question is about how the Nest packages are wired.
- When must you call signAsync() instead of sign()?Whenever `secretOrKeyProvider` can return a promise, for example when it fetches a key from a secret store. The synchronous `sign()` cannot wait, so it logs a warning pointing to `signAsync` and throws `WrongSecretProviderError`. The same applies to `verify()` and `verifyAsync()`.
- Does setting verifyOptions on JwtModule change what AuthGuard('jwt') accepts?No. `AuthGuard('jwt')` runs the passport-jwt strategy, which verifies with the options given to its own `super()` call: `secretOrKey`, plus any `issuer`, `audience`, `algorithms`, `ignoreExpiration` or `jsonWebTokenOptions`. `JwtModule`'s `verifyOptions` apply only to `JwtService.verify()` and `verifyAsync()`.
- Why might jwtService.sign('order-42') throw?A string payload is allowed only when the effective sign options contain nothing but `secret` or `privateKey`. If the module sets `signOptions: { expiresIn: '15m' }`, that option is merged in and the call throws an error listing it. Sign an object payload instead.
- JwtModule.register() can inject ConfigService into its options object
- AuthGuard('jwt') verifies tokens with the JwtService configured in JwtModule
- Options passed to sign() are ignored once the module sets signOptions
- sign() handles an async secretOrKeyProvider by waiting for the key
- JwtService has to be added to the providers of each module that injects it