0
0
NestJSframework~10 mins

JWT strategy in NestJS - Step-by-Step Execution

Choose your learning style9 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.