0
0
NestJSframework~5 mins

Passport.js integration in NestJS

Choose your learning style9 modes available
Introduction

Passport.js helps you add login and user verification easily. It works with NestJS to keep your app safe.

You want users to log in with username and password.
You want to allow login using social accounts like Google or Facebook.
You need to protect certain parts of your app so only logged-in users can access.
You want to manage user sessions or tokens securely.
You want a simple way to add many login methods without much code.
Syntax
NestJS
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'local' })],
  providers: [AuthService, LocalStrategy],
  controllers: [AuthController],
})
export class AuthModule {}

Use PassportModule.register() to set default login strategy.

Provide strategy classes like LocalStrategy to define how login works.

Examples
This defines a local login strategy checking username and password.
NestJS
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
This controller uses the local strategy to protect the login route.
NestJS
import { Controller, Post, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  @UseGuards(AuthGuard('local'))
  @Post('login')
  async login(@Request() req) {
    return req.user;
  }
}
Sample Program

This example shows a simple NestJS module using Passport.js local strategy. It checks username and password from a fixed list and returns the user if valid. The login route is protected and returns user info on success.

NestJS
import { Module, Injectable, Controller, Post, UseGuards, Request } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthGuard } from '@nestjs/passport';
import { UnauthorizedException } from '@nestjs/common';

@Injectable()
class AuthService {
  private users = [{ username: 'john', password: 'changeme' }];

  async validateUser(username: string, password: string): Promise<any> {
    const user = this.users.find(u => u.username === username && u.password === password);
    return user ? { username: user.username } : null;
  }
}

@Injectable()
class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

@Controller('auth')
class AuthController {
  @UseGuards(AuthGuard('local'))
  @Post('login')
  login(@Request() req) {
    return req.user;
  }
}

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'local' })],
  providers: [AuthService, LocalStrategy],
  controllers: [AuthController],
})
export class AuthModule {}
OutputSuccess
Important Notes

Always handle errors like unauthorized access to keep your app safe.

Use HTTPS in production to protect user credentials during login.

Passport.js supports many strategies; you can add social logins easily.

Summary

Passport.js helps add login and user verification in NestJS apps.

Define strategies to control how users log in.

Protect routes using guards that check user login status.