Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 42 ยท The Request Pipeline

Guards and Authorization

Learn NestJS guards: implement CanActivate, read metadata with Reflector and SetMetadata, build a roles guard, and mark public routes under a global auth guard.

A guard decides whether a request may continue to the route handler. It answers one question, yes or no, and runs after middleware and before interceptors and pipes. Guards are the Nest way to implement authentication checks ("who are you?") and authorization checks ("are you allowed to do this?").

Unlike middleware, a guard receives an ExecutionContext: an object that knows which class and which handler are about to run. That is what makes declarative rules possible. You can tag a route with @Roles('admin') and have one generic guard read that tag, instead of writing role checks inside every method.

The Nest code in this lesson is read-only (it needs Node and npm). The runnable stand-ins rebuild the important ideas, metadata, a reflector, and a chain of guards, in plain JavaScript so you can watch the decisions being made.

What a guard returns

true The request continues.
false Nest answers 403 Forbidden.
throw Your own exception, such as 401.

Guards can also return a promise or an observable.

1 / 2

A first guard

A guard is an @Injectable() class that implements CanActivate:

TypeScript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly tokens: TokenService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const header: string | undefined = request.headers['authorization'];
    const token = header?.startsWith('Bearer ') ? header.slice(7) : undefined;
    if (!token) throw new UnauthorizedException();

    request.user = await this.tokens.verify(token); // throws if invalid
    return true;
  }
}

If canActivate returns false, Nest responds with 403 Forbidden. If you throw an exception, that exception's response is used instead, which is how you produce 401 Unauthorized for a missing or bad token. The convention is: 401 means "I do not know who you are", 403 means "I know who you are, and the answer is no".

Because guards are classes created by the injector, they can take services in the constructor, such as the token service above. Attaching request.user is the usual way to pass the identity to later guards and to the handler. Where the token comes from is covered in Authentication with JWT.

Binding guards

TypeScript
@Controller('cats')
@UseGuards(AuthGuard)              // every route in this controller
export class CatsController {
  @Post()
  @UseGuards(RolesGuard)           // this route also needs RolesGuard
  create() { /* ... */ }
}

@UseGuards(A, B) runs A then B, and stops at the first one that refuses. There is also a global form. app.useGlobalGuards(new AuthGuard()) works but sits outside dependency injection, so a guard with a constructor dependency should be registered as a provider with the APP_GUARD token instead:

TypeScript
@Module({
  providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
})
export class AuthModule {}

The order of global, controller and route guards is global first, then controller, then route.

The ExecutionContext

ExecutionContext extends ArgumentsHost. The parts you use most:

Method Returns
switchToHttp().getRequest() The underlying request (Express or Fastify)
switchToHttp().getResponse() The underlying response
getHandler() A reference to the method that will run
getClass() The controller class
getType() 'http', 'rpc' or 'ws'

The same guard code can therefore run for HTTP controllers, microservice handlers and WebSocket gateways, which you will meet in WebSockets and Gateways.

Metadata and the Reflector

Hard-coding roles inside a guard would force you to write a new guard for every route. Instead, attach metadata to routes with SetMetadata, wrapped in a small decorator of your own:

TypeScript
import { SetMetadata } from '@nestjs/common';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
TypeScript
@Controller('users')
@Roles('staff')
export class UsersController {
  @Get()
  list() { /* staff may call this */ }

  @Delete(':id')
  @Roles('admin')                  // overrides the class-level tag
  remove() { /* only admins */ }
}

The guard reads the tags with the Reflector helper:

TypeScript
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!required) return true; // route is not tagged: no role needed

    const { user } = context.switchToHttp().getRequest();
    return required.some((role) => user?.roles?.includes(role));
  }
}

The three reading methods differ in how they combine the handler's and the class's values:

Method Behavior
get(key, target) Reads one target only
getAllAndOverride(key, [handler, class]) The first target that defines the key wins, so method beats class
getAllAndMerge(key, [handler, class]) Merges arrays (or objects) from both

Public routes under a global guard

A common pattern is to protect everything by default and mark exceptions. You register an auth guard globally and add a @Public() decorator:

TypeScript
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
TypeScript
canActivate(context: ExecutionContext) {
  const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
    context.getHandler(),
    context.getClass(),
  ]);
  if (isPublic) return true;
  // ...verify the token
}

Now a new controller is secure the moment you create it, and a route like POST /auth/login opts out with one line. Forgetting a decorator then fails closed (the route is protected) rather than open, which is the safer default.

Stand-in: metadata, a reflector and a guard chain

The first stand-in is not Nest's implementation. It stores metadata on handler and class objects in a Map, offers getAllAndOverride, and runs a global auth guard followed by a roles guard over a set of fake requests. It reproduces the decision logic, status codes and the @Public() pattern.

JS Auth and roles guards driven by metadata

Press Run (or Ctrl + Enter) to see the console output here.

No output.

login is public, so both guards wave it through (the roles guard checks the flag too, because the class-level staff tag would otherwise apply to it). list inherits the class-level staff tag. remove has its own admin tag, which overrides the class tag because the handler is searched first.

Stand-in: override versus merge, and short-circuit order

The second stand-in makes the difference between getAllAndOverride and getAllAndMerge visible, and proves that a guard chain stops at the first refusal.

JS Override vs merge, and chain order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With override only admin is required. With merge any of admin, staff or support would satisfy the rule, so choose the method that matches what you mean. The third guard never ran because the second refused.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A guard's canActivate returns false. What status code does Nest send by default?

    A plain false produces a ForbiddenException. To send 401 you throw an UnauthorizedException yourself.
  2. 2. Why does a guard get an ExecutionContext while middleware does not?

    By the time guards run, Nest knows which controller and method will handle the request, so getClass() and getHandler() work.
  3. 3. Both a controller and one of its methods carry @Roles(...) with different values. Which Reflector call lets the method's value win?

    getAllAndOverride returns the first target that defines the key, so list the handler before the class.
  4. 4. Why is a global auth guard plus a @Public() decorator considered a safe pattern?

    Routes are secure by default and exceptions must be declared, so a mistake fails closed.
  5. 5. Where should you register a guard that needs injected services and must apply to the whole app?

    useGlobalGuards(new ...) happens outside the injector, while APP_GUARD lets Nest build the guard with its dependencies.

Summary

  • A guard implements CanActivate, returns true to continue and false for a 403, or throws to choose its own response (401 for unknown callers).
  • Guards run after middleware and before interceptors, pipes and the handler.
  • ExecutionContext exposes the request, the handler and the class.
  • SetMetadata plus Reflector lets one generic guard enforce declarative rules such as @Roles(); mind override versus merge.
  • Protect everything with a global guard (APP_GUARD) and mark exceptions with @Public().

Continue with Interceptors, which wrap the handler on the way in and the way out.