skip to content

Roles & Policy Guards

Authorization in Nest is a guard reading role metadata, or v12's policy classes checked by @Can() with undeclared routes denied. Interviewers ask why authentication's guard must run first.

on this pageshow

explore

questions

5

In a NestJS app, how do you restrict a route to certain roles with a custom @Roles() decorator and a roles guard?

level: juniorimportance: must knowfreq 65%

answer

  1. metadata first, enforcement second
  2. createDecorator or SetMetadata
  3. guard compares with request.user
  4. a false return means Forbidden

basics

~20 s

Create a Roles decorator with Reflector.createDecorator() or SetMetadata(), put it on the handler, and write a CanActivate guard that reads it through Reflector and compares it with request.user's roles; a false return makes Nest answer 403.

solid answer

~40 s

A `Roles` decorator built with `Reflector.createDecorator<string[]>()`, or a wrapper around `SetMetadata('roles', roles)` from `@nestjs/common`, only attaches metadata; it enforces nothing. The enforcement is a `RolesGuard` implementing `CanActivate`: it injects `Reflector`, reads the roles required by the handler (with `getAllAndOverride`, the controller's as a fallback), takes the user that authentication put on `request.user`, and returns whether that user holds one of them. When `canActivate` returns `false`, Nest throws a `ForbiddenException`, so the client gets a 403 with `"Forbidden resource"`. Two traps: the docs' sample returns `true` when a route has no `@Roles()`, so a forgotten decorator leaves the route open, and the guard assumes `request.user` is already set, so it must run after the authentication guard.

code

typescript · 22 lines
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

export const Roles = Reflector.createDecorator<string[]>();

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

  canActivate(context: ExecutionContext): boolean {
    // The method's @Roles() wins; the controller's applies when the method has none.
    const required = this.reflector.getAllAndOverride(Roles, [context.getHandler(), context.getClass()]);
    if (!required) {
      return true; // no @Roles(): this guard does not restrict the route
    }
    const { user } = context.switchToHttp().getRequest();
    if (!user) {
      throw new UnauthorizedException(); // not signed in: 401, not 403
    }
    return required.some((role) => user.roles.includes(role)); // false: Nest answers 403
  }
}

go deeper

for a junior

Recall the two pieces: a decorator that only stores the required roles, and a CanActivate guard that reads them and compares them with request.user. Know that returning false gives a 403.

for a middle

Explain how the guard reads metadata from the handler and the class, why getAllAndOverride matters for controller defaults, and when to throw UnauthorizedException instead of returning false.

for a senior

Point out the fail-open default of the sample guard and the dependency on authentication having run first, and say how you would catch a forgotten decorator before production.

for a principal

Frame roles as a coarse, route-level tool: decide where a team needs record-level rules and a deny-by-default convention, and whether a hand-written guard still carries that weight.

## Two pieces: metadata and a guard In NestJS, restricting a route to certain roles takes two separate pieces. A **decorator** records which roles the route requires, as metadata on the handler or on the controller class. A **guard**, a class implementing `CanActivate`, reads that metadata on every request and decides whether the handler runs. The decorator on its own enforces nothing: a `@Roles(['admin'])` that no guard reads is a comment. The guard needs a third input that it does not produce itself: the **current user**. By convention the authentication step (a Passport guard, the first-party authentication package, or your own middleware) attaches the signed-in user to `request.user`, roles included. The roles guard only compares. ## Defining the decorator Nest offers two ways to attach the metadata: | Approach | Declaration | Usage | Read back with | |---|---|---|---| | `Reflector.createDecorator` from `@nestjs/core` | `Reflector.createDecorator<string[]>()` | `@Roles(['staff', 'admin'])`, one typed argument | `reflector.get(Roles, target)` | | `SetMetadata` from `@nestjs/common` | `(...roles: string[]) => SetMetadata('roles', roles)` | `@Roles('staff', 'admin')`, any arguments you design | `reflector.get('roles', target)` | - With `Reflector.createDecorator()`, the decorator object itself is the metadata key, and its type parameter types both the argument and the value the guard reads back. - With `SetMetadata`, you choose the key and the value, so a decorator can take several arguments. The docs advise wrapping it in your own decorator rather than writing `@SetMetadata('roles', [...])` on routes. ## Writing the guard A roles guard does four things on each request: 1. Injects `Reflector` and reads the required roles for the route: from the handler (`context.getHandler()`) and, for a controller-wide default, from the class (`context.getClass()`). 2. Returns `true` when the route declares no roles, if that is the rule you choose (the docs' sample does exactly this). 3. Reads the user from `context.switchToHttp().getRequest().user`. 4. Returns whether the user holds a required role. The matching rule (any role, all roles, a hierarchy) is yours: the docs call theirs `matchRoles()` and point out that Nest does not provide it. `reflector.get(Roles, context.getHandler())` reads the method only, so a class-level `@Roles()` is invisible to it. To let the controller set a default that a method overrides, read both targets with `getAllAndOverride`, which returns the first defined value in the order you pass the targets. The `Reflector` methods themselves belong with guards in general; here they are simply how the roles guard reads its input. ## What the client sees When `canActivate()` returns `false`, Nest throws a `ForbiddenException`, and the default exception handling sends: ```json { "statusCode": 403, "message": "Forbidden resource", "error": "Forbidden" } ``` To answer differently, throw an exception from the guard yourself. The usual case is a request with no user at all: that caller is not forbidden, they are not signed in, so `throw new UnauthorizedException()` (a 401) is the more accurate answer. Anything a guard throws goes through the exception filters like any other error. ## Binding it, and the traps The guard runs only where it is bound: `@UseGuards(RolesGuard)` on a controller or a method, or globally as an `APP_GUARD` provider. The binding mechanics are general guard material; for roles, these are the traps interviewers probe: - **Open by default.** The docs' sample returns `true` when a route has no `@Roles()`, so a forgotten decorator leaves the route open to everyone who got past authentication. If that is not acceptable, invert the rule: deny when no roles are declared, and mark open routes explicitly. - **No user yet.** The guard assumes `request.user` is already set. If it runs before authentication, the docs' sample reads `user.roles` on `undefined`, throws a `TypeError`, and the caller gets a 500; a version written with optional chaining denies everyone with a 403 instead. Either way the fix is guard order, not more code in the roles guard. - **Handler-only reads.** `reflector.get()` on the handler never sees a class-level `@Roles()`. - **Roles are coarse.** A roles guard answers "may staff call this route?". It cannot answer "may this customer see this particular order?", which depends on the record; that check belongs in the code that loads the order. The NestJS 12 docs point to a policy package for per-record rules and a deny-by-default stance, but the hand-written roles guard remains the building block interviewers expect a candidate to write from memory.

  • When would you build the roles decorator with SetMetadata instead of Reflector.createDecorator?
    `Reflector.createDecorator()` gives one typed argument and hides the key. `SetMetadata('roles', roles)` from `@nestjs/common` lets you pick the key and the value, so a wrapper like `(...roles: string[]) => SetMetadata('roles', roles)` can take several arguments, as in `@Roles('staff', 'admin')`. The guard then reads it with `reflector.get('roles', context.getHandler())`. The docs recommend wrapping `SetMetadata` in your own decorator rather than calling it on routes directly.
  • Why throw UnauthorizedException from the roles guard instead of returning false when request.user is missing?
    Returning `false` always produces a `ForbiddenException`, a 403, which tells the client that the answer is no for them. A caller without a user has not been identified at all, so a 401 telling them to authenticate is more accurate. Throwing `UnauthorizedException` from `canActivate` sends it through the exception filters like any other error. Ideally the authentication guard has already rejected such a request before the roles guard runs.
  • How would you make a route with no @Roles() denied rather than open?
    Change the guard's branch for missing metadata: instead of `return true`, return `false` (or throw), and add an explicit marker for routes everyone may call, read the same way through `Reflector`. That turns a forgotten decorator into a 403 found in testing instead of an open route found in production. The cost is that every route, including health checks, must now declare something.

  • The @Roles() decorator by itself blocks callers who lack the role.
  • A guard that returns false makes Nest answer 401 Unauthorized.
  • The docs' RolesGuard denies a route that has no @Roles() metadata.
  • reflector.get() on the handler also picks up roles set on the controller.
  • Nest ships a matchRoles() helper that compares required and granted roles.
  • A roles guard can safely run before the authentication guard.
open as a page

In a NestJS 12 app, why must the authentication guard run before a roles or policy guard, and what decides which global guard runs first?

level: middleimportance: must knowfreq 50%

basics

~20 s

Role and policy guards read the user that authentication puts on request.user, so run first they see nobody. Global guards precede controller and route guards; singleton APP_GUARD providers run in module-scan order, before app.useGlobalGuards() ones.

open as a page

In a NestJS 12 app using @nestjs/authorization, how do @Policy() classes, @Can() and authorize() split an orders API's checks?

level: middleimportance: should knowfreq 25%

basics

~20 s

A @Policy() class holds abilities, methods taking the user that return true to allow. @Can() checks an ability in the global guard before the handler, for rules needing no record; authorize() checks it in the service after loading the order.

open as a page

In a NestJS 12 app using @nestjs/authorization, why does one route answer a guest 401 and a customer 403, and why does a new unannotated route deny everyone?

level: seniorimportance: should knowfreq 22%

basics

~20 s

A guest reaches policies as a null user, so a denial is a 401 (signing in might change it); a signed-in user's denial is a 403. The global AuthorizationGuard denies every handler that declares no @Can(), @Can.Anyone() or @Public().

open as a page

Your NestJS 12 services each hand-roll a @Roles() guard; would you standardise on @nestjs/authorization's deny-by-default policies, and what would the switch cost the team?

level: principalimportance: nice to knowfreq 12%

basics

~20 s

Adopt it where record-level rules and a closed-by-default stance matter: a forgotten @Can() closes a route instead of opening it. The cost is a declaration on every handler, strict guard ordering, singleton policies and a new dependency to track.

open as a page