Muhammed Ulvi Özkaya
Blog
Blog
NestJSTypeScriptBackend

JWT Authentication with NestJS

April 30, 2026

1 min read

A practical guide to implementing stateless JWT authentication in NestJS using Guards, Passport strategies, and protected routes.


JWT (JSON Web Token) is a compact, stateless authentication mechanism widely used in REST APIs. NestJS makes it straightforward to implement with its built-in Guards and Passport integration.

Installation

npm install @nestjs/jwt @nestjs/passport passport passport-jwt
npm install -D @types/passport-jwt

Setting Up the Auth Module

Configure JwtModule with a secret and expiration:

JwtModule.register({
  secret: process.env.JWT_SECRET,
  signOptions: { expiresIn: '7d' },
})

JWT Strategy

The strategy validates the token and extracts the payload on every protected request:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET,
    });
  }

async validate(payload: { sub: string; email: string }) {
return { id: payload.sub, email: payload.email };
}
}

Protecting Routes

Apply the JwtAuthGuard to any controller or route that requires authentication:

@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req) {
  return req.user;
}

Conclusion

NestJS + JWT provides a clean, decorator-driven authentication layer that scales well across large APIs.


© 2026 Muhammed Ulvi Ozkaya. All rights reserved.