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.