Skip to content

Guard (backend)

Medium — good to knowBackend

ELI5 — The Vibe Check

A guard is a checkpoint that decides whether a request should proceed or be rejected — like a bouncer with a guest list. It runs before the route handler and returns true (let them in) or false (kick them out). Guards handle authorization: 'you might be logged in, but are you ALLOWED to do this?'

Real Talk

In backend frameworks like NestJS, a guard is a class that implements a canActivate() method to determine if a request should be handled. Guards run after middleware but before interceptors and pipe validation. They're used for authentication, role-based access control (RBAC), and feature flags. They can be applied at the controller, method, or global level.

Show Me The Code

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
    const user = context.switchToHttp().getRequest().user;
    return requiredRoles.some((role) => user.roles.includes(role));
  }
}

@UseGuards(RolesGuard)
@Roles('admin')
@Get('users')
getUsers() { }

When You'll Hear This

"Add an admin guard to that endpoint — only admins should access it." / "The auth guard runs before the roles guard in NestJS."

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