0
0
NestJSframework~30 mins

JWT authentication guard in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
JWT Authentication Guard in NestJS
📖 Scenario: You are building a secure API using NestJS. You want to protect certain routes so only users with a valid JWT token can access them.
🎯 Goal: Create a JWT authentication guard that checks if the incoming request has a valid JWT token and allows access only if the token is valid.
📋 What You'll Learn
Create a JWT payload interface
Create a JWT authentication guard class
Use the CanActivate interface and ExecutionContext
Validate the JWT token from the request headers
Allow access only if the token is valid
💡 Why This Matters
🌍 Real World
JWT authentication guards are used in real APIs to protect sensitive routes and ensure only authorized users can access them.
💼 Career
Understanding how to implement JWT guards is essential for backend developers working with NestJS or similar frameworks to build secure applications.
Progress0 / 4 steps
1
Create the JWT payload interface
Create an interface called JwtPayload with a single string property userId.
NestJS
Need a hint?

Interfaces define the shape of data. Here, JwtPayload will represent the data inside the JWT token.

2
Create the JWT authentication guard class
Create a class called JwtAuthGuard that implements CanActivate from @nestjs/common. Import CanActivate and ExecutionContext from @nestjs/common.
NestJS
Need a hint?

The guard class must implement CanActivate and have a canActivate method that returns a boolean.

3
Extract and validate the JWT token
Inside the canActivate method, get the request object from context.switchToHttp().getRequest(). Extract the authorization header from request.headers. Return false if the header is missing or does not start with 'Bearer '. Otherwise, extract the token string after 'Bearer '.
NestJS
Need a hint?

The JWT token is usually sent in the Authorization header as Bearer <token>. We check this format before extracting the token.

4
Validate the JWT token and complete the guard
Import verify from jsonwebtoken. Inside canActivate, use verify(token, 'secretKey') to decode the token. If verification throws an error, return false. If successful, attach the decoded payload to request.user and return true. Use a try-catch block for error handling.
NestJS
Need a hint?

Use verify to check the token. If it fails, deny access. If it passes, save the user info for later use.