0
0
NestJSframework~5 mins

JWT strategy in NestJS

Choose your learning style9 modes available
Introduction

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.

When you want users to log in once and stay logged in safely.
When you need to protect parts of your app so only logged-in users can see them.
When you want to send a token to the user that proves their identity.
When building APIs that need secure user authentication.
When you want to avoid storing user sessions on the server.
Syntax
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.

Examples
Use environment variables for the secret key to keep it safe and not hard-coded.
NestJS
super({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.JWT_SECRET,
});
Customize the returned user data based on what your app needs from the token.
NestJS
async validate(payload: any) {
  return { id: payload.sub, email: payload.email };
}
Sample Program

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.

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: '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' }
OutputSuccess
Important Notes

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.

Summary

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.