0
0
NestJSframework~30 mins

JWT strategy in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
JWT Strategy Implementation in NestJS
📖 Scenario: You are building a simple authentication system for a web app using NestJS. You want to protect certain routes so only users with a valid JWT token can access them.
🎯 Goal: Create a JWT authentication strategy in NestJS that validates JWT tokens and extracts user information from them.
📋 What You'll Learn
Create a JWT strategy class extending PassportStrategy
Configure the JWT secret key
Implement the validate method to extract user data from the token
Register the JWT strategy as a provider
💡 Why This Matters
🌍 Real World
JWT strategies are used in real apps to secure routes by verifying user identity through tokens.
💼 Career
Understanding JWT strategy implementation is essential for backend developers working with authentication in NestJS.
Progress0 / 4 steps
1
Create the JWT strategy class
Create a class called JwtStrategy that extends PassportStrategy(Strategy) from @nestjs/passport. Import Strategy from passport-jwt. Inside the constructor, call super() with an empty object for now.
NestJS
Need a hint?

Remember to import Strategy from passport-jwt and extend PassportStrategy(Strategy).

2
Configure the JWT secret key
Update the super() call inside the JwtStrategy constructor to include the jwtFromRequest option using ExtractJwt.fromAuthHeaderAsBearerToken() and set the secretOrKey option to the string 'topSecret51'. Import ExtractJwt from passport-jwt.
NestJS
Need a hint?

Use ExtractJwt.fromAuthHeaderAsBearerToken() to get the token from the request header.

3
Implement the validate method
Add an async method called validate that takes a single parameter payload. This method should return an object containing the userId and username properties from the payload.
NestJS
Need a hint?

The validate method extracts user info from the JWT payload. Use payload.sub for userId.

4
Register the JWT strategy provider
Export the JwtStrategy class and ensure it is decorated with @Injectable() so it can be registered as a provider in your module.
NestJS
Need a hint?

Make sure the class has the @Injectable() decorator so NestJS can inject it as a provider.