A NestJS route behind the JWT guard always answers 401
{"message":"Unauthorized","statusCode":401}Short answer
The guard answers 401 when Passport finds no token, cannot verify it, or the token is expired. Send the token as an Authorization Bearer header, make the signing and verifying secret identical, check the expiry, and make sure the guard names the same strategy you registered.
Fix it fast
1Find out which cause you have
Call the protected route with curl and the exact token, so you see the answer without the client app in the way.
curl -i http://localhost:3000/profile -H "Authorization: Bearer <access_token>"2Match what you see, then jump to its fix
- 1
The route answers 401 only from your client, and the curl call above worksThe token is not sent as a Bearer headerFix - 2
401 on a fresh token that has not expiredThe secret used to sign differs from the one used to verifyFix - 3
401 appears some time after login, and works again after a new loginThe token has expiredFix - 4
401 on every request, and validate() is never calledThe guard names a different strategy than the one registeredFix
- 1
What does the error look like?
{"message":"Unauthorized","statusCode":401}
Cause 1 of 4
The token is not sent as a Bearer header
1Check
The strategy reads the token with ExtractJwt.fromAuthHeaderAsBearerToken(), so the header must be Authorization: Bearer <token>, with one space and no quotes around the token.
curl -i http://localhost:3000/profile2Fix
Send the header in exactly that form from the client, or change jwtFromRequest if you pass the token another way.
fetch('/profile', {
headers: { Authorization: `Bearer ${accessToken}` },
});3Verify
The route returns your profile data.
curl -i http://localhost:3000/profile -H "Authorization: Bearer <access_token>"Confirmed by docs.nestjs.com
Cause 2 of 4
The secret used to sign differs from the one used to verify
1Check
The strategy's secretOrKey must be the same secret that JwtModule signs with. An environment variable that is empty or loaded later in one place gives a mismatch.
grep -rn "secret" src2Fix
Use one shared constant or ConfigService value in both JwtModule.register and the strategy's super() call.
// jwt.strategy.ts
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});3Verify
Log in again to get a new token and call the route.
curl -i http://localhost:3000/profile -H "Authorization: Bearer <new_token>"Confirmed by docs.nestjs.com
Cause 3 of 4
The token has expired
1Check
Decode the payload and compare the exp claim (seconds since 1970) with the current time. The Nest guide's sample lifetime is 60 seconds.
date +%s2Fix
Set a lifetime that fits your app in signOptions, and refresh tokens before they run out.
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '15m' },
})3Verify
A token from a new login keeps working past the old limit.
curl -i http://localhost:3000/profile -H "Authorization: Bearer <new_token>"Confirmed by docs.nestjs.com
Cause 4 of 4
The guard names a different strategy than the one registered
1Check
AuthGuard('jwt') looks up the strategy registered as jwt. The strategy class must extend PassportStrategy(Strategy) from passport-jwt and be in the module's providers.
grep -rn "AuthGuard\|PassportStrategy\|providers:" src2Fix
Keep the default name, or pass the same name in both places, and add the strategy to providers.
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@Module({ providers: [AuthService, JwtStrategy] })
export class AuthModule {}3Verify
A request with a valid token reaches the controller and request.user is set.
curl -i http://localhost:3000/profile -H "Authorization: Bearer <access_token>"Confirmed by docs.nestjs.com
How do I stop it coming back?
- Keep the secret in one config value and read it in both the signing and the verifying code.
- Return the user object from validate(): what it returns becomes request.user.
- Test the protected route with curl after every change to the auth module.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Back end
TypeScript cannot find module '@nestjs/core' or its type declarations
error TS2307: Cannot find module '@nestjs/common' or its corresponding type declarations.
TS2307 means TypeScript searched node_modules and found neither the package nor its types.
3 causes, each with a fixBack end
Node.js in Docker Compose cannot reach MySQL on 127.0.0.1:3306
Error: connect ECONNREFUSED 127.0.0.1:3306
Inside a container, 127.0.0.1 is that container, not MySQL.
3 causes, each with a fixBack end
NestJS GraphQL cannot work out the output type of a field or query
Cannot determine a GraphQL output type for the "<name>". Make sure your class is decorated with an appropriate decorator.
In code-first mode Nest reads TypeScript types through decorators, and arrays, promises and unions disappear at runtime.
2 causes, each with a fixBack end
IntelliJ IDEA breakpoints are ignored in a NestJS app
No 'Debugger listening' line appears when the NestJS app starts
IntelliJ can only debug a NestJS app when the Node.js process runs with the inspector on and the IDE attaches to its port.
4 causes, each with a fixBack end
The nest command is not found in the terminal
bash: nest: command not found
The shell cannot find a nest executable on its PATH.
3 causes, each with a fixBack end
NestJS watch mode does not restart after I save a file
Changes show on the host but not in the running container
Watch mode only sees files that exist inside the process that runs it.
3 causes, each with a fix