0
0
NestjsHow-ToBeginner ยท 4 min read

How to Use Passport with NestJS for Authentication

To use passport with nestjs, install @nestjs/passport and passport packages, then create a strategy class extending PassportStrategy. Register the strategy in a module and use @UseGuards(AuthGuard('strategy-name')) to protect routes.
๐Ÿ“

Syntax

Using Passport in NestJS involves these parts:

  • Strategy class: Extends PassportStrategy and implements validation logic.
  • AuthGuard: Protects routes by checking authentication.
  • Module setup: Registers the strategy and imports PassportModule.
typescript
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    // Validate user credentials
    return { userId: 1, username };
  }
}
๐Ÿ’ป

Example

This example shows how to set up a local username/password strategy with Passport in NestJS, protect a route, and validate users.

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

@Injectable()
class LocalStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    if (username === 'user' && password === 'pass') {
      return { userId: 1, username };
    }
    return null;
  }
}

@Controller()
class AppController {
  @UseGuards(AuthGuard('local'))
  @Post('login')
  login(@Request() req) {
    return { message: 'Logged in', user: req.user };
  }
}

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'local' })],
  controllers: [AppController],
  providers: [LocalStrategy],
})
export class AppModule {}
Output
{"message":"Logged in","user":{"userId":1,"username":"user"}}
โš ๏ธ

Common Pitfalls

Common mistakes when using Passport with NestJS include:

  • Not calling super() in the strategy constructor.
  • Forgetting to register the strategy provider in the module.
  • Using the wrong strategy name in @UseGuards(AuthGuard('strategy-name')).
  • Not returning a user object in validate, causing authentication to fail silently.
typescript
/* Wrong: Missing super() call */
class BadStrategy extends PassportStrategy(Strategy) {
  constructor() {
    // super() missing here
  }

  async validate() {
    return { id: 1 };
  }
}

/* Right: Include super() call */
class GoodStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super();
  }

  async validate() {
    return { id: 1 };
  }
}
๐Ÿ“Š

Quick Reference

Summary tips for using Passport with NestJS:

  • Install @nestjs/passport and passport packages.
  • Create strategy classes extending PassportStrategy.
  • Register strategies in your module providers.
  • Use @UseGuards(AuthGuard('strategy-name')) to protect routes.
  • Return user info in validate method for successful authentication.
โœ…

Key Takeaways

Install and import @nestjs/passport and passport packages to start.
Create a strategy class extending PassportStrategy and implement validate().
Register the strategy in your module providers array.
Use @UseGuards(AuthGuard('strategy-name')) to secure routes.
Always return a user object in validate() to authenticate successfully.