JWT Authentication in NestJS: The Simple Setup

Salonisuman
3 min readSep 22, 2024

--

Photo by AltumCode on Unsplash

Authentication can be one of the trickiest parts of developing a secure app, but with NestJS, it’s surprisingly simple. I’ve recently implemented JWT (JSON Web Token) authentication in a project, and it’s safe to say NestJS has made this process a breeze. Let’s walk through a quick setup that can get you up and running in minutes.

1. Setting Up the Auth Module

First, we need to generate an AuthModule where all authentication-related logic will live. With NestJS's CLI, this is as simple as:

nest g resource auth

This will create a modular structure for handling authentication, keeping our code organized. The AuthService handles the business logic, while the AuthController manages API routes.

2. JWT Setup

JWT is perfect for stateless authentication, allowing the server to verify user tokens without maintaining session state. Let’s start by installing the required packages:

npm install @nestjs/jwt passport-jwt
npm install --save-dev @types/passport-jwt

Next, configure the JwtModule with a secret key and expiration time:

import { JwtModule } from '@nestjs/jwt';
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';

@Module({
imports: [
JwtModule.register({
secret: 'supersecretkey', // Change this to a secure key
signOptions: { expiresIn: '60m' }, // Tokens expire in 60 minutes
}),
],
controllers: [AuthController],
providers: [AuthService],
})
export class AuthModule {}

This configuration enables JWT-based authentication with a 60-minute expiration time for tokens.

3. Implementing the Auth Logic

Now, inside the auth.service.ts file, add the logic to validate users and generate tokens.This method allows you to generate a token when valid credentials are provided. The login() method returns a JWT signed with the user’s information.

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}

async validateUser(username: string, pass: string): Promise<any> {
// Replace this with real user validation logic
if (username === 'admin' && pass === 'password') {
return { username };
}
return null;
}

async login(user: any) {
const payload = { username: user.username };
return {
access_token: this.jwtService.sign(payload),
};
}
}

4. Protect Routes with JWT Guard

Now, let’s protect our routes using Passport.js and guards. First, install the required packages and Create a guard to handle JWT token validation:

npm install @nestjs/passport passport passport-jwt
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

Finally, secure your routes by applying the guard in your auth.controller.ts:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from './jwt-auth.guard';

@Controller('profile')
export class AuthController {
@UseGuards(JwtAuthGuard)
@Get()
getProfile() {
return { message: 'This is a protected route' };
}
}

By using the @UseGuards() decorator, we ensure that only authenticated users with valid JWT tokens can access this route.

While NestJS simplifies authentication, a potential downside is the added learning curve due to its modular structure and reliance on decorators, guards, and external libraries like Passport.js. For beginners, setting up advanced features like OAuth or custom strategies can feel a bit overwhelming at first.

What I appreciate the most is the ability to apply guards to protect routes. You get a clean, declarative way to enforce authentication without littering your code with conditional checks. Instead of spending hours configuring middleware or manually managing session states, I can rely on NestJS’s elegant guard system to handle the hard part.

--

--

Salonisuman
Salonisuman

Written by Salonisuman

Software Engineer | Talks about Technology

No responses yet