0
0
NestjsHow-ToBeginner ยท 4 min read

How to Use JWT Strategy in NestJS for Authentication

In NestJS, use the PassportModule with the JwtStrategy class to handle JWT authentication. Define a strategy by extending PassportStrategy with passport-jwt, then protect routes using the @UseGuards(AuthGuard('jwt')) decorator.
๐Ÿ“

Syntax

The JWT strategy in NestJS involves creating a class that extends PassportStrategy from @nestjs/passport and uses the Strategy from passport-jwt. You configure it with options like jwtFromRequest to extract the token and secretOrKey to verify it.

Then, implement a validate method that receives the decoded JWT payload and returns user data for request handling.

typescript
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 };
  }
}
๐Ÿ’ป

Example

This example shows a simple NestJS module using JWT strategy for authentication. It includes the strategy, a guard to protect routes, and a controller with a protected route.

typescript
import { Module, Controller, Get, UseGuards, Request } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthGuard } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Controller('profile')
export class ProfileController {
  @UseGuards(AuthGuard('jwt'))
  @Get()
  getProfile(@Request() req) {
    return req.user;
  }
}

@Module({
  imports: [
    PassportModule,
    JwtModule.register({
      secret: 'yourSecretKey',
      signOptions: { expiresIn: '60m' },
    }),
  ],
  controllers: [ProfileController],
  providers: [JwtStrategy],
})
export class AppModule {}
Output
GET /profile with valid JWT returns user info from token payload
โš ๏ธ

Common Pitfalls

  • Forgetting to register JwtStrategy in the module providers causes authentication to fail.
  • Using a different secret key for signing and verifying JWTs will reject tokens.
  • Not extracting the token correctly (e.g., wrong header or method) leads to unauthorized errors.
  • Missing @UseGuards(AuthGuard('jwt')) on routes means they are not protected.
typescript
/* Wrong: Missing JwtStrategy provider */
@Module({
  imports: [PassportModule, JwtModule.register({ secret: 'key' })],
  controllers: [ProfileController],
  providers: [], // JwtStrategy missing here
})
export class AppModule {}

/* Right: Include JwtStrategy */
@Module({
  imports: [PassportModule, JwtModule.register({ secret: 'key' })],
  controllers: [ProfileController],
  providers: [JwtStrategy],
})
export class AppModule {}
๐Ÿ“Š

Quick Reference

Remember these key points when using JWT strategy in NestJS:

  • Use ExtractJwt.fromAuthHeaderAsBearerToken() to get token from Authorization header.
  • Keep your JWT secret key safe and consistent.
  • Implement validate() to return user info from token payload.
  • Protect routes with @UseGuards(AuthGuard('jwt')).
โœ…

Key Takeaways

Extend PassportStrategy with passport-jwt to create JwtStrategy in NestJS.
Configure token extraction and secret key correctly in JwtStrategy constructor.
Use @UseGuards(AuthGuard('jwt')) to protect routes with JWT authentication.
Always register JwtStrategy in your module providers to enable it.
Implement validate() method to extract and return user data from JWT payload.