Protecting an endpoint

You need to be sure to import the AuthModule into the imports array in the module you want to use Auth.

To secure a route, use the Nest decorator @UseGuards(), and passport's AuthGuard() function as follows:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  @UseGuards(AuthGuard())
  getHello(): string {
    return this.appService.getHello();
  }
}

You can use this decorator at controller level or route level to protect all or only some endpoints.

Last updated