In a NestJS app, how do you restrict a route to certain roles with a custom @Roles() decorator and a roles guard?
answer
- metadata first, enforcement second
- createDecorator or SetMetadata
- guard compares with request.user
- a false return means Forbidden
basics
~20 sCreate 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 sA `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 linesimport { 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
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.
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.
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.
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.