Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

NestJS Guards: CanActivate, ExecutionContext, and Reflector

NestJS guards decide whether a request can reach a handler. Learn how CanActivate, ExecutionContext, and Reflector fit together, including metadata precedence, transport-aware access, and guard scope.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A NestJS guard is a route-aware gate: it decides whether a request may proceed to a handler. A guard implements CanActivate; its canActivate() method uses ExecutionContext to identify what is about to run and can use Reflector to read authorization metadata on the handler or controller. This makes guards a natural place to enforce authorization after identity has been established.

What a NestJS guard does—and when it runs

NestJS runs guards after middleware and before pipes. Unlike middleware, a guard receives route execution context, so it can make a decision based on the specific handler or controller that will receive the request. The NestJS v10 Guards documentation describes this route-aware role.

As an Amazon Associate I earn from qualifying purchases.

A guard implements the CanActivate interface. Its canActivate() method can return a boolean, a Promise of a boolean, or an Observable of a boolean. A true result allows processing to continue; false denies access. In the v10 documentation, returning false causes Nest to throw an HttpException. Throw a specific exception from the guard if the application needs a different response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authentication and authorization are related but distinct. Authentication establishes who the user is; authorization decides whether that user may invoke a route. A guard can use a user placed on the request by an earlier authentication step, or participate in the authentication flow itself. The mechanism that establishes identity depends on the application.

How CanActivate and ExecutionContext work together

ExecutionContext extends ArgumentsHost. It exposes the handler about to execute through getHandler(), the controller class through getClass(), and methods for accessing arguments associated with the active transport. The NestJS v11 Execution context documentation explains these APIs.

  • context.getHandler() identifies the route handler method.
  • context.getClass() identifies the controller class.
  • context.switchToHttp().getRequest() accesses an HTTP request when the active transport is HTTP.

Do not assume every guard invocation has an HTTP request. For RPC, WebSockets, or GraphQL, use the relevant framework integration and the argument shape for that transport. A guard can be transport-aware, but an HTTP-specific access pattern is not transport-neutral.

Use Reflector to read handler and controller metadata

Metadata lets a shared guard apply route-specific policies without hard-coding each handler. For example, a roles decorator can attach a required role to a controller or method. Inject Reflector and read that metadata in the guard.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reflector.get() reads a value from one target. When both a handler and controller may define the same metadata key, use getAllAndOverride() or getAllAndMerge() with the intended targets. For a method-level value to take precedence over a controller-level value, put context.getHandler() first, followed by context.getClass().

  • getAllAndOverride(key, [handler, controller]) returns the first defined value in target order. A handler value therefore overrides the controller value.
  • getAllAndMerge(key, [handler, controller]) combines values from the targets instead of selecting one. This is useful when method and controller requirements should accumulate.

Choose deliberately: override means the narrower method policy replaces the broader controller policy; merge means both contribute. The NestJS v11 Reflector reference documents these retrieval patterns.

Example: a role guard with method-over-controller precedence

This illustrative HTTP guard assumes an earlier authentication step has associated a user with the request. The roles decorator and user shape are application-specific; adapt them to the project’s authentication and policy model.

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

const ROLES_KEY = 'roles';

type Role = 'reader' | 'editor' | 'admin';

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

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requiredRoles?.length) {
      return true;
    }

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

The empty-metadata case above permits the request; an application may instead choose a default-deny policy. The example uses some(), so a user needs at least one listed role. If policy requires every role, use an all-required check instead. These are authorization decisions, not behaviors imposed by NestJS.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose a guard scope and registration pattern

NestJS supports method-, controller-, and application-level guards. Use the narrowest scope that matches the policy, while keeping a shared guard reusable through metadata where appropriate. The v10 Guards documentation shows guard binding, and the v10 Authorization documentation demonstrates a roles-based pattern.

  • Method: apply a guard to one route handler when only that operation needs the policy.
  • Controller: apply it to a controller when its routes share the same guard.
  • Application: register it globally when it should apply throughout the application.

For a global guard, app.useGlobalGuards() is an application-level option. If the guard needs module-managed dependency injection, use the APP_GUARD provider pattern shown in the NestJS authentication documentation. Choose based on how the application constructs and scopes providers rather than treating the two registration styles as interchangeable.

Version and transport considerations

The API concepts here draw on NestJS v10 guard and authorization pages and v11 execution-context documentation; the authentication registration example is from the v8 documentation. These references establish the concepts, not that every example is identical across majors. Check the documentation matching the NestJS version installed in the project before adopting exact code.

For GraphQL, RPC, and WebSockets, adapt argument access to the relevant integration and transport. The controller/handler distinction and metadata-selection choices remain useful, but an HTTP request lookup does not become valid in a non-HTTP context automatically.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.