Bird
Raised Fist0
NestJSframework~10 mins

JWT strategy in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - JWT strategy
Client sends login request
↓
Server verifies user credentials
↓
Server creates JWT token
↓
Client stores JWT token
↓
Client sends request with JWT in header
↓
JWT Strategy extracts token
↓
JWT Strategy verifies token signature and expiry
↓
Allow access
This flow shows how JWT strategy in NestJS checks a token from client requests to allow or deny access.
Execution Sample
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: 'secretKey',
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}
This code defines a JWT strategy that extracts and verifies JWT tokens from request headers.
Execution Table
StepActionInput/StateOutput/Result
1Client sends login requestUser credentialsCredentials received by server
2Server verifies credentialsCredentialsValid user or error
3Server creates JWT tokenUser infoJWT token with payload and signature
4Client stores JWT tokenJWT tokenToken saved in client storage
5Client sends request with JWTJWT in Authorization headerRequest with token arrives at server
6JWT Strategy extracts tokenRequest headersExtracted JWT token string
7JWT Strategy verifies tokenJWT token stringValid token or invalid error
8If valid, validate() runsToken payloadUser info object returned
9If invalid, access deniedInvalid tokenUnauthorized error response
10Request proceeds with user infoUser info from validate()Access granted to protected route
💡 Execution stops if token is invalid or missing, denying access.
Variable Tracker
VariableStartAfter Step 3After Step 6After Step 7After Step 8Final
credentialsundefineduser inputuser inputuser inputuser inputused for token creation
jwtTokenundefinedcreated JWT stringcreated JWT stringverified JWT stringverified JWT stringpassed to validate()
payloadundefinedundefinedundefinedextracted from JWTpayload objectuser info returned
userInfoundefinedundefinedundefinedundefined{ userId, username }used for access control
Key Moments - 3 Insights
Why does the JWT strategy extract the token from the Authorization header?
Because the JWT is sent by the client in the Authorization header as a Bearer token, the strategy must extract it from there to verify it, as shown in step 6 of the execution_table.
What happens if the JWT token is expired or invalid?
The strategy rejects the token during verification (step 7), causing the request to be denied with an unauthorized error, stopping further execution as noted in the exit_note.
Why does the validate() method return user info?
The validate() method receives the decoded token payload and returns user info so that NestJS can attach it to the request, allowing protected routes to know who the user is, as shown in step 8 and 10.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the JWT token get created?
AStep 8
BStep 6
CStep 3
DStep 10
💡 Hint
Check the 'Action' column for 'Server creates JWT token' in the execution_table.
According to variable_tracker, what is the value of 'payload' after step 7?
Aundefined
Bextracted from JWT
Cuser input
Dcreated JWT string
💡 Hint
Look at the 'payload' row and the 'After Step 7' column in variable_tracker.
If the token is invalid, what happens according to the execution_table?
AAccess denied with unauthorized error
BRequest proceeds with user info
CJWT Strategy extracts token
DServer creates JWT token
💡 Hint
See step 9 in the execution_table for the invalid token case.
Concept Snapshot
JWT Strategy in NestJS:
- Extracts JWT from Authorization header
- Verifies token signature and expiry
- On valid token, validate() returns user info
- On invalid token, denies access
- Used to protect routes by confirming user identity
Full Transcript
This visual execution trace shows how the JWT strategy in NestJS works step-by-step. First, the client sends login credentials to the server. The server verifies these credentials and creates a JWT token containing user info. The client stores this token and sends it with future requests in the Authorization header. The JWT strategy extracts the token from the header, verifies its signature and expiry. If valid, the validate() method returns user info from the token payload, allowing access to protected routes. If invalid, the request is denied with an unauthorized error. Variables like credentials, jwtToken, payload, and userInfo change state through these steps, helping track the flow. Key moments clarify why the token is extracted from headers, what happens on invalid tokens, and the purpose of validate(). The quizzes test understanding of token creation, payload extraction, and invalid token handling. This helps beginners see exactly how JWT strategy processes tokens to secure NestJS applications.

Practice

(1/5)
1. What is the main purpose of the JWT strategy in a NestJS application?
easy
A. To encrypt user passwords before saving to the database
B. To manage database connections securely
C. To verify user identity by checking the JWT token in requests
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand JWT strategy role

    The JWT strategy is used to check the user's identity by verifying the token sent with requests.
  2. 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.
  3. Final Answer:

    To verify user identity by checking the JWT token in requests -> Option C
  4. Quick Check:

    JWT strategy = verify token [OK]
Hint: JWT strategy always verifies tokens to identify users [OK]
Common Mistakes:
  • Confusing JWT strategy with password encryption
  • Thinking JWT handles static file serving
  • Mixing JWT with database connection management
2. Which of the following is the correct way to import the Passport JWT strategy in a NestJS file?
easy
A. import { JwtStrategy } from 'passport-jwt';
B. import { JwtStrategy } from '@nestjs/jwt';
C. import { JwtStrategy } from '@nestjs/passport';
D. import { JwtStrategy } from 'jsonwebtoken';

Solution

  1. Step 1: Identify correct package for JwtStrategy

    In NestJS, JwtStrategy is usually imported from 'passport-jwt' which provides the Passport JWT strategy.
  2. 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.
  3. Final Answer:

    import { JwtStrategy } from 'passport-jwt'; -> Option A
  4. Quick Check:

    JwtStrategy import = 'passport-jwt' [OK]
Hint: JwtStrategy comes from 'passport-jwt' package in NestJS [OK]
Common Mistakes:
  • Importing JwtStrategy from '@nestjs/jwt'
  • Confusing JwtStrategy with jsonwebtoken functions
  • Using '@nestjs/passport' for JwtStrategy import
3. Given this JwtStrategy validate method, what will be returned if the token payload is { userId: 5, username: 'alice' }?
async validate(payload: any) {
  return { id: payload.userId, name: payload.username };
}
medium
A. { id: 5, name: 'alice' }
B. { userId: 5, username: 'alice' }
C. undefined
D. Throws an error because of missing return type

Solution

  1. 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'.
  2. Step 2: Apply payload values

    Payload has userId=5 and username='alice', so returned object is { id: 5, name: 'alice' }.
  3. Final Answer:

    { id: 5, name: 'alice' } -> Option A
  4. Quick Check:

    Validate returns mapped user info [OK]
Hint: Validate returns a new object with selected payload fields [OK]
Common Mistakes:
  • Returning the original payload instead of mapped object
  • Assuming undefined return without explicit return
  • Thinking missing return type causes runtime error
4. Identify the error in this JwtStrategy constructor code snippet:
constructor(private readonly jwtService: JwtService) {
  super({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.JWT_SECRET,
  });
}
medium
A. Missing call to super() with options object
B. process.env.JWT_SECRET might be undefined causing runtime error
C. jwtFromRequest should be a function, not a method call
D. JwtService should not be injected in JwtStrategy constructor

Solution

  1. Step 1: Review constructor usage

    The constructor correctly calls super() with options including jwtFromRequest and secretOrKey.
  2. 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.
  3. Final Answer:

    process.env.JWT_SECRET might be undefined causing runtime error -> Option B
  4. Quick Check:

    Missing JWT secret causes runtime failure [OK]
Hint: Always ensure JWT_SECRET env variable is set before running [OK]
Common Mistakes:
  • Assuming jwtFromRequest is incorrectly used
  • Thinking JwtService injection is invalid here
  • Ignoring possibility of missing environment variables
5. You want to create a custom JwtStrategy that extracts the user role from the token and denies access if the role is not 'admin'. Which approach correctly implements this logic?
hard
A. Modify jwtFromRequest to only accept tokens with 'admin' role
B. Set secretOrKey to 'admin' in constructor options to restrict roles
C. Use a guard to check user role after JwtStrategy validation without modifying validate()
D. Override validate() to check payload.role and throw UnauthorizedException if not 'admin'

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Override validate() to check payload.role and throw UnauthorizedException if not 'admin' -> Option D
  4. Quick Check:

    Role check belongs in validate() method [OK]
Hint: Check roles inside validate() and throw exception if unauthorized [OK]
Common Mistakes:
  • Confusing secretOrKey with role filtering
  • Trying to filter roles in jwtFromRequest extractor
  • Ignoring validate() as place for access control
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard