nestjs/nest · error · UnauthorizedException
Unauthorized
Error message
Unauthorized
What it means
Error "Unauthorized" thrown in nestjs/nest.
Source
Thrown at sample/19-auth-jwt/src/auth/auth.guard.ts:33
constructor(
private jwtService: JwtService,
private reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
// 💡 See this condition
return true;
}
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: jwtConstants.secret,
});
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}View on GitHub (pinned to 6ec0e2783d)
Solutions
- Send a valid JWT in the Authorization: Bearer <token> header; the guard throws Unauthorized when the token is missing or invalid.
- Verify the token has not expired and was signed with the expected secret (jwtConstants.secret).
- Ensure the Authorization header is formatted exactly as 'Bearer <token>'.
Example fix
// client request
fetch('/profile', {
headers: { Authorization: `Bearer ${accessToken}` }
}); When it happens
Trigger: Thrown at sample/19-auth-jwt/src/auth/auth.guard.ts:33 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of nestjs/nest@6ec0e2783d (2026-08-03).
Data as JSON: /data/errors/deed89a37b89ec77.json.
Report an issue: GitHub.