Skip to main content

AuthGuard

Package: @nauth-toolkit/nestjs Type: Guard

NestJS guard that validates the access token, checks session status, and attaches req.user.

import { AuthGuard } from '@nauth-toolkit/nestjs';

Methods

canActivate()

async canActivate(context: ExecutionContext): Promise<boolean>
AuthGuard Throws Exceptions

The guard throws NAuthException on auth failures. It does not return false.

Optional authentication on @Public() routes

On routes marked with @Public(), AuthGuard allows the request through. If a valid token is present, it will still attach req.user so @CurrentUser() works. If the token is missing/invalid/expired, it will not throw and req.user will be undefined.

To make an endpoint "public, but optionally authenticated", combine @Public() with @UseGuards(AuthGuard):

import { Controller, Get, UseGuards, Query } from '@nestjs/common';
import { AuthGuard, AuthService, CurrentUser, LogoutDTO, Public } from '@nauth-toolkit/nestjs';
import type { IUser } from '@nauth-toolkit/nestjs';

@Controller('auth')
export class ExampleController {
constructor(private readonly authService: AuthService) {}

@Public()
@UseGuards(AuthGuard)
@Get('logout')
async logout(
@CurrentUser() user: IUser | undefined,
@Query('forgetMe') forgetMe?: string,
): Promise<{ success: true }> {
// Logout is idempotent:
// - If the user is authenticated, this revokes the current session.
// - If the user is already logged out/expired, it still succeeds and clears cookies (cookies/hybrid mode).
const dto = new LogoutDTO();
dto.forgetMe = forgetMe === 'true' || forgetMe === '1';
if (user) {
// Optional: validate that the logout targets the authenticated user (never accept sub from the client).
dto.sub = user.sub;
}
return await this.authService.logout(dto);
}
}

Errors

CodeWhenDetails
BEARER_NOT_ALLOWEDBearer disallowedundefined
COOKIES_NOT_ALLOWEDCookies disallowedundefined
SESSION_EXPIREDSession expiredundefined
SESSION_NOT_FOUNDSession missingundefined
TOKEN_INVALIDMissing/invalid tokenundefined

Throws NAuthException with the codes listed above (protected routes only).

Example (inherit without constructor deps)

import { Injectable, ExecutionContext, ForbiddenException, UseGuards, Controller, Get } from '@nestjs/common';
import { AuthGuard } from '@nauth-toolkit/nestjs';
import type { IUser } from '@nauth-toolkit/nestjs';

@Injectable()
export class VerifiedEmailGuard extends AuthGuard {
async canActivate(context: ExecutionContext): Promise<boolean> {
await super.canActivate(context);

const req = context.switchToHttp().getRequest<{ user: IUser }>();
if (!req.user.isEmailVerified) {
throw new ForbiddenException('Email verification required');
}
return true;
}
}

@Controller('profile')
@UseGuards(VerifiedEmailGuard)
export class ProfileController {
@Get()
getProfile(): { ok: true } {
return { ok: true };
}
}