skip to content

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%

answer

  1. open versus closed by default
  2. route checks and record checks
  3. every handler declares something
  4. guard order becomes load-bearing
  5. migrate from the startup log

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.

solid answer

~50 s

For NestJS 12 codebases with real record-level rules, I would standardise on `@nestjs/authorization`: its global guard denies any handler that declares nothing, abilities are type-checked, record checks with `authorize()` live in services that workers share, guests get 401 and signed-in users 403, and denials are auditable through `AuthorizationEvents`. The costs are a declaration on every handler, with each `@Can.Anyone()` needing review; load-bearing guard order, with Passport or `useGlobalGuards()` authentication only logged or invisible to the startup check; singleton policies; errors that become 500s outside handlers; and a new dependency to track. I would migrate from the startup log of denied handlers, opening legacy controllers with `@Can.Anyone()` briefly while the old roles guard still enforces. For a small service with coarse staff-versus-everyone rules, a roles guard that denies when no roles are declared may be enough.

go deeper

for a junior

Recall the headline difference: a hand-rolled roles guard usually lets an undecorated route through, while the policy package's guard refuses it.

for a middle

Explain what a team would rewrite: @Roles() into @Can() abilities, service-level record checks into authorize(), and @Can.Anyone() on routes that check elsewhere.

for a senior

Name the operational risks of the switch, guard order with non-first-party authentication, 500s from authorize() in guards, other transports, and how to test each.

for a principal

Make the call with its cost: weigh closed-by-default and typed record checks against a codebase-wide convention change and a new dependency, and plan a staged migration.

## The decision A codebase where each service hand-rolls a `@Roles()` guard works, and many teams never outgrow it. The NestJS 12 docs now teach a first-party alternative, `@nestjs/authorization`, built around policy classes, `@Can()` and a deny-by-default global guard. Standardising on it is a lead's call because it changes what every route author must write, and the cost lands on the whole team rather than on one service. ## What the package gives that a roles guard does not | Concern | Hand-rolled roles guard | `@nestjs/authorization` | |---|---|---| | A route with no declaration | open in the docs' sample, which returns `true` without roles | denied, and listed in the startup log | | Record rules ("own orders only") | ad hoc code in each service | abilities that take the record, checked with `authorize()` | | Guests versus forbidden users | 403 unless you throw a 401 yourself | 401 for a `null` user, 403 for a signed-in one | | Misspelled permission names | found at runtime, unless you type the role strings | ability names checked at compile time | | Admin bypass | an extra clause in every check | one `before()` hook per policy | | Auditing denials | your own logging | `AuthorizationEvents` with policy, ability and reason | | Startup validation | none | an unregistered policy, or `AuthenticationGuard` running second, stops the app | The strongest argument is the default. With a roles guard, a forgotten decorator opens a route; with the package, it closes one. ## What it costs - **Every handler must declare something.** Routes that check in services, or need no permission, carry `@Can.Anyone()`, and each one is a place a reviewer must confirm a service-level check exists. The docs' production checklist says to review every `@Can.Anyone()`. - **Guard order becomes load-bearing.** With `@nestjs/authentication`, a wrong import order stops the app. With a Passport guard, the check only guesses by class name and logs; an authentication guard added with `app.useGlobalGuards()` runs after the authorization guard and is invisible to the check. Move it to a singleton `APP_GUARD`, and keep an end-to-end test that signs in and calls a `@Can()` route. - **Policies must be singletons.** Per-request state goes into ability arguments, never into the policy. - **Errors change shape.** `authorize()` throws a transport-neutral `AuthorizationError`; thrown from your own guards or middleware it becomes a 500, so those must use `can()`. - **Other transports need configuration.** A hybrid app's message handlers are guarded only when connected with `inheritAppConfig: true`; GraphQL field resolvers need `fieldResolverEnhancers: ['guards']`. - **A new dependency.** Weigh the package's maturity and rate of change as you would any recently introduced library, against a roles guard of a few dozen lines that nobody has to upgrade. ## A migration that keeps production working 1. Install the package once authentication is registered as a singleton global guard, ahead of the authorization module. 2. Read the startup error log: it names every handler the guard will now deny. That list is the worklist. 3. Put `@Can.Anyone()` on legacy controllers so their routes keep working while the existing `RolesGuard` still enforces roles. New controllers are deny-by-default from day one, but a handler added to a legacy controller is open again, so keep this window short. 4. Controller by controller, replace `@Roles()` with policies: route-level abilities in `@Can()`, record checks moved into services with `authorize()`, then remove that controller's `@Can.Anyone()`. 5. Alternatively, roll out per controller with `globalGuard: false` and `@UseGuards(JwtAuthGuard, AuthorizationGuard)`, your authentication guard first, at the price of the default not covering new code until you switch the global guard on. ## When not to switch - A small service whose rules really are "staff routes versus everyone else" gains little beyond the default, and changing the roles guard to deny when no roles are declared captures most of that. - A team that cannot yet commit to the guard-ordering discipline and to reviewing every `@Can.Anyone()` trades one class of bug for another. - Rules that need an external policy engine or a relationship store are a different decision, made outside the framework. The judgment is whether the default flip and typed, record-aware checks are worth a codebase-wide change in convention, and whether the team will keep the review discipline the package assumes.

  • What evidence would make you keep the hand-rolled roles guard?
    Rules that are genuinely route-level (staff versus everyone), no record-level checks scattered across services, and no history of routes shipped without a role decorator. Then a one-line change, denying when no roles are declared, captures the main benefit without a new dependency or a codebase-wide convention change.
  • How do you stop @Can.Anyone() from becoming the new way to bypass authorization?
    Treat each one as a claim that the service authorizes, or that the route needs no permission, and review it as such. Prefer `@Can()` with an argument resolver for checks on an id in the URL, so a later edit to the handler cannot drop them, and keep an end-to-end test per sensitive route that a forbidden user gets a 403.

  • Adopting the package is a drop-in swap that needs no route changes.
  • Deny-by-default removes the need to review routes marked @Can.Anyone().
  • The startup check guarantees the right order for any authentication guard.
  • Policies can cache per-request data because each request gets its own instance.
  • Every service benefits equally, whatever its rules look like.

Assumes NestJS 12, whose security docs introduce @nestjs/authorization; the hand-written roles guard is the guards chapter's pattern.