JWT strategy helps your app check if a user is who they say they are using a secure token. It keeps your app safe by allowing only the right users to access certain parts.
JWT strategy in NestJS
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'yourSecretKey', }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }
The jwtFromRequest tells where to find the token, usually in the Authorization header as a Bearer token.
The validate method runs after the token is checked and returns user info for the app to use.
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
});async validate(payload: any) { return { id: payload.sub, email: payload.email }; }
This JwtStrategy class checks the JWT token from the request header. If the token is valid, it extracts the user ID and username from the token payload and returns it. This info can then be used in your app to know who the user is.
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'mySuperSecret', }); } async validate(payload: any) { // This runs after token is verified return { userId: payload.sub, username: payload.username }; } } // Example payload: { sub: 123, username: 'alice' } // When a request comes with a valid JWT, validate returns { userId: 123, username: 'alice' }
Always keep your secret key safe and never share it publicly.
Use HTTPS to protect tokens during transmission.
Tokens usually expire; handle token expiration in your app.
JWT strategy checks user identity using tokens sent in requests.
It extracts user info from the token to use in your app.
Keep your secret key safe and use environment variables.
Practice
Solution
Step 1: Understand JWT strategy role
The JWT strategy is used to check the user's identity by verifying the token sent with requests.Step 2: Compare options with JWT purpose
Only To verify user identity by checking the JWT token in requests matches this purpose; others relate to different concerns like encryption or static files.Final Answer:
To verify user identity by checking the JWT token in requests -> Option CQuick Check:
JWT strategy = verify token [OK]
- Confusing JWT strategy with password encryption
- Thinking JWT handles static file serving
- Mixing JWT with database connection management
Solution
Step 1: Identify correct package for JwtStrategy
In NestJS, JwtStrategy is usually imported from 'passport-jwt' which provides the Passport JWT strategy.Step 2: Check other imports
'@nestjs/jwt' provides JWT utilities like JwtService but not JwtStrategy itself; '@nestjs/passport' provides Passport integration but not JwtStrategy; 'jsonwebtoken' is for token creation/verification, not strategy.Final Answer:
import { JwtStrategy } from 'passport-jwt'; -> Option AQuick Check:
JwtStrategy import = 'passport-jwt' [OK]
- Importing JwtStrategy from '@nestjs/jwt'
- Confusing JwtStrategy with jsonwebtoken functions
- Using '@nestjs/passport' for JwtStrategy import
async validate(payload: any) {
return { id: payload.userId, name: payload.username };
}Solution
Step 1: Analyze the validate method
The method takes the payload and returns a new object with keys 'id' and 'name' mapped from 'userId' and 'username'.Step 2: Apply payload values
Payload has userId=5 and username='alice', so returned object is { id: 5, name: 'alice' }.Final Answer:
{ id: 5, name: 'alice' } -> Option AQuick Check:
Validate returns mapped user info [OK]
- Returning the original payload instead of mapped object
- Assuming undefined return without explicit return
- Thinking missing return type causes runtime error
constructor(private readonly jwtService: JwtService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
});
}Solution
Step 1: Review constructor usage
The constructor correctly calls super() with options including jwtFromRequest and secretOrKey.Step 2: Check environment variable usage
If process.env.JWT_SECRET is undefined, the strategy will fail at runtime because the secret key is missing.Final Answer:
process.env.JWT_SECRET might be undefined causing runtime error -> Option BQuick Check:
Missing JWT secret causes runtime failure [OK]
- Assuming jwtFromRequest is incorrectly used
- Thinking JwtService injection is invalid here
- Ignoring possibility of missing environment variables
Solution
Step 1: Understand role check in JwtStrategy
The validate() method is the right place to inspect the token payload and enforce role-based access by throwing exceptions if conditions fail.Step 2: Evaluate other options
Setting secretOrKey to 'admin' is incorrect because it expects a secret key, not a role; guards can check roles but the question asks for JwtStrategy implementation; jwtFromRequest only extracts tokens, it cannot filter by role.Final Answer:
Override validate() to check payload.role and throw UnauthorizedException if not 'admin' -> Option DQuick Check:
Role check belongs in validate() method [OK]
- Confusing secretOrKey with role filtering
- Trying to filter roles in jwtFromRequest extractor
- Ignoring validate() as place for access control
Ready to prove it?
Pass the test and this pattern moves unknown
