Skip to content

Guard

Medium — good to knowBackend

ELI5 — The Vibe Check

A guard in NestJS is a gatekeeper that decides if a request should be allowed through. Auth guards check if you're logged in. Role guards check if you're an admin. If the guard says no, the request is rejected before it ever reaches the handler. No guard, no entry.

Real Talk

In NestJS, guards are classes that implement the CanActivate interface to determine whether a request should be processed. They run after middleware but before interceptors and pipes, making them ideal for authentication and authorization logic. Guards have access to the execution context and can use decorators for role-based or permission-based access control.

Show Me The Code

@Injectable()
class RoleGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const roles = Reflect.getMetadata('roles', context.getHandler());
    const user = context.switchToHttp().getRequest().user;
    return roles.includes(user.role);
  }
}

@UseGuards(RoleGuard)
@Roles('admin')
@Get('admin/dashboard')
async getDashboard() { /* ... */ }

When You'll Hear This

"The auth guard rejects requests without a valid JWT." / "Use role guards to restrict admin endpoints to admin users only."

Made with passive-aggressive love by manoga.digital. Powered by Claude.