0
0
NestJSframework~10 mins

Passport.js integration in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Passport.js integration
Start NestJS App
Import Passport Module
Define Strategy (e.g., JWT)
Register Strategy with Passport
Use @UseGuards(AuthGuard('jwt'))
Request comes in
Passport validates user
Allow or deny access
Response sent
This flow shows how NestJS integrates Passport.js by importing modules, defining strategies, guarding routes, and validating users on requests.
Execution Sample
NestJS
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } 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 for Passport in NestJS that extracts the token from the header and validates the payload.
Execution Table
StepActionInputOutputNotes
1Start NestJS appNoneApp runningNestJS app boots up
2Import PassportModulePassportModulePassport integratedPassport features available
3Define JwtStrategyJWT configStrategy readyStrategy knows how to extract and verify token
4Register JwtStrategyJwtStrategy classStrategy registeredPassport uses this strategy
5Apply @UseGuards(AuthGuard('jwt'))Controller routeRoute guardedOnly requests with valid JWT allowed
6Incoming request with JWTRequest headers with tokenToken extractedJwtStrategy extracts token
7JwtStrategy validate() calledJWT payloadUser object returnedPayload verified and user info returned
8Access granted to routeValidated userRoute handler runsUser can access protected resource
9Response sentRoute outputHTTP responseClient receives data
10Incoming request without JWTRequest headers missing tokenNo token foundAccess denied
11Access deniedNo valid user401 UnauthorizedClient blocked from route
💡 Execution stops when request is either authorized or denied based on JWT presence and validity.
Variable Tracker
VariableStartAfter Step 6After Step 7Final
jwtTokenundefinedBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...SameUsed for validation
payloadundefinedundefined{ sub: 1, username: 'user1' }Extracted from token
userundefinedundefined{ userId: 1, username: 'user1' }Returned by validate()
Key Moments - 3 Insights
Why does the validate() method return a user object?
Because Passport uses the returned user object to attach it to the request, allowing route handlers to access authenticated user info (see execution_table step 7).
What happens if the JWT token is missing or invalid?
The guard denies access and returns 401 Unauthorized, stopping the request before reaching the route handler (see execution_table steps 10 and 11).
How does Passport know which strategy to use for a route?
The @UseGuards decorator specifies the strategy name like 'jwt', linking the route to the registered JwtStrategy (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 7 when validate() is called?
A401 Unauthorized error
BUser object with userId and username
CRaw JWT token string
DUndefined
💡 Hint
Check the 'Output' column in execution_table row for step 7.
At which step does the route become guarded by Passport's JWT strategy?
AStep 5
BStep 3
CStep 6
DStep 9
💡 Hint
Look for when @UseGuards(AuthGuard('jwt')) is applied in execution_table.
If the JWT token is missing in the request, what is the final response sent?
ARoute handler output
BUser object
C401 Unauthorized
DEmpty response
💡 Hint
See execution_table steps 10 and 11 for missing token scenario.
Concept Snapshot
Passport.js integration in NestJS:
- Import PassportModule and register strategies
- Define strategy classes (e.g., JwtStrategy) with validate()
- Use @UseGuards(AuthGuard('strategyName')) on routes
- Passport extracts token, validates user, attaches user to request
- Guards block unauthorized access automatically
Full Transcript
This visual execution trace shows how Passport.js integrates with NestJS. The app starts and imports PassportModule. A JwtStrategy is defined to extract and verify JWT tokens from request headers. This strategy is registered with Passport. Routes are protected using the @UseGuards decorator with AuthGuard('jwt'). When a request arrives, Passport extracts the token, calls validate() to verify the payload, and returns a user object. If valid, the route handler runs with user info attached. If the token is missing or invalid, Passport denies access and returns a 401 Unauthorized response. Variables like jwtToken, payload, and user change as the request flows through these steps. Key moments include understanding validate()'s role, what happens on missing tokens, and how guards link strategies to routes. The quiz tests understanding of these steps and outputs.