How to Use AuthGuard in NestJS for Route Protection
In NestJS, use
AuthGuard to protect routes by applying it as a guard on controllers or route handlers. It works by checking user authentication before allowing access, typically with strategies like JWT or local authentication.Syntax
The AuthGuard is a class that you apply using the @UseGuards() decorator on controllers or methods. You specify the authentication strategy name as a string argument to AuthGuard, like AuthGuard('jwt'). This tells NestJS which strategy to use for authentication checks.
Example parts:
@UseGuards(AuthGuard('jwt')): Applies the guard using the JWT strategy.AuthGuard: The guard class imported from@nestjs/passport.- Controller or method: Where you want to protect access.
typescript
import { Controller, Get, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('profile') export class ProfileController { @UseGuards(AuthGuard('jwt')) @Get() getProfile() { return { message: 'This route is protected' }; } }
Example
This example shows a simple NestJS controller with a route protected by AuthGuard('jwt'). Only requests with a valid JWT token can access the /profile route.
typescript
import { Controller, Get, UseGuards, Req } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('profile') export class ProfileController { @UseGuards(AuthGuard('jwt')) @Get() getProfile(@Req() req) { return { user: req.user, message: 'Access granted to protected route' }; } } // Assume JWT strategy is configured properly in the app module and passport setup.
Output
{ user: { /* user info from JWT */ }, message: 'Access granted to protected route' }
Common Pitfalls
- Not importing
AuthGuardfrom@nestjs/passportcauses errors. - Forgetting to register the authentication strategy (like JWT) in the module will make the guard fail.
- Applying
@UseGuards(AuthGuard('jwt'))without a valid token in the request will block access with a 401 Unauthorized error. - Not using
@Req()or@Request()to access the authenticated user inside the handler.
typescript
/* Wrong: Missing strategy registration */ @UseGuards(AuthGuard('jwt')) @Get() getProfile() { return { message: 'This will fail if JWT strategy is not set up' }; } /* Right: Register JWT strategy and import AuthGuard correctly */
Quick Reference
Summary tips for using AuthGuard in NestJS:
- Import
AuthGuardfrom@nestjs/passport. - Use
@UseGuards(AuthGuard('strategyName'))on controllers or routes. - Ensure the authentication strategy (e.g., JWT) is configured and registered.
- Access authenticated user info via
@Req()in route handlers. - Handle unauthorized requests gracefully with exception filters or global guards.
Key Takeaways
Use @UseGuards(AuthGuard('strategy')) to protect routes with authentication in NestJS.
Always configure and register the authentication strategy before using AuthGuard.
Access the authenticated user via @Req() inside guarded route handlers.
Unauthorized requests without valid credentials will be blocked automatically.
Import AuthGuard from @nestjs/passport to use it correctly.