skip to content

First-Party Auth Module

Nest 12's own authentication package closes every route behind a global guard, resolves users via credential providers you register and keeps sessions in your store. Interviewers probe its defaults.

on this pageshow

explore

questions

5

In a NestJS 12 app importing AuthenticationModule from @nestjs/authentication, why does a new health-check route answer 401, and how do you open it?

level: juniorimportance: should knowfreq 30%

answer

  1. deny by default
  2. what forRoot() adds as APP_GUARD
  3. globalGuard defaults to true
  4. a decorator that skips every provider

basics

~20 s

AuthenticationModule.forRoot() registers AuthenticationGuard as a global guard by default, so every route needs a signed-in user and anonymous calls get 401. Marking the health route @Public() makes the guard skip it: no credential provider runs.

solid answer

~40 s

In NestJS 12, importing `AuthenticationModule.forRoot()` adds `AuthenticationGuard` as an `APP_GUARD` (the `globalGuard` option defaults to `true`), so every route requires a user and an anonymous call gets `401` with `errorCode` `missing_credentials`. To open a route, put `@Public()` from `@nestjs/authentication` on the method or the controller: the guard returns `true` without running any credential provider, and `@CurrentUser()` is `null`. Under a `@Public()` class, `@Authenticate()` on one method makes it require a user again. If a route should serve guests and signed-in users alike, use `@Authenticate({ optional: true })` instead: guests pass with a `null` user, while credentials that are present but invalid still get a `401`. With `globalGuard: false` the default flips, and routes stay open until they use `@UseGuards(AuthenticationGuard)`.

code

typescript · 19 lines
typescript
import { Controller, Get } from '@nestjs/common';
import { Authenticate, CurrentUser, Public } from '@nestjs/authentication';
import type { User } from '../users/user.js';

@Public()
@Controller('status')
export class StatusController {
  @Get('health')
  health() {
    return { status: 'ok' };
  }

  // Under a @Public() class, @Authenticate() requires a user again.
  @Authenticate()
  @Get('me')
  me(@CurrentUser() user: User) {
    return user;
  }
}

go deeper

for a junior

Recall that the module protects every route by default and that @Public() from the authentication package opens one; name the 401 an anonymous caller gets.

for a middle

Explain how forRoot() registers the guard through APP_GUARD, why @Public() means no provider runs and a null current user, and how optional differs.

for a senior

Show you would keep the deny-by-default guard, audit which routes are public, and choose optional over public wherever the response depends on the caller.

for a principal

Frame globalGuard: false as a fail-open choice and argue for a convention, such as reviewing every @Public() in code review, that keeps the default safe.

## What the module registers `@nestjs/authentication` is NestJS 12's first-party sign-in package. Importing `AuthenticationModule.forRoot()` does more than make services injectable: through its `globalGuard` option, which defaults to `true`, the module adds `AuthenticationGuard` to the application as an `APP_GUARD` provider. A **global guard** runs before every route handler in the app, whichever module declares the controller. From that moment the app is **deny by default**: every route requires a signed-in user. The guard asks the registered **credential providers** (classes that read a session cookie, a bearer token or an API key and return a user) whether the request proves anyone. When none does, the guard refuses with `401` and a machine-readable code: ```json {"message":"Unauthorized","statusCode":401,"errorCode":"missing_credentials"} ``` So a freshly added `GET /health` answers `401` to the load balancer's probe, which carries no cookie. Nothing is wrong with the route; the module is doing exactly what it promises. The module also logs a warning at startup when no credential provider has registered at all, because then every route that is not public answers `401`. ## Opening a route with @Public() `@Public()`, exported by `@nestjs/authentication`, marks a method or a whole controller as open. On a public route the guard returns `true` at once: - **No credential provider runs**, so no session is read and no store is queried. - **`@CurrentUser()` is `null`**, even if the caller happens to send a valid session cookie. - Typical uses are health checks, a public catalog and the routes that sign users in or up. ```typescript import { Controller, Get } from '@nestjs/common'; import { Authenticate, Public } from '@nestjs/authentication'; @Controller('health') export class HealthController { @Public() @Get() check() { return { status: 'ok' }; } } ``` The decorator works at class level too. Method options are merged over class options field by field, and `@Authenticate()` explicitly sets the route back to non-public, so one method of a `@Public()` controller can still require a user. ## Public, optional and required compared | Route marking | No credentials | Valid credentials | Present but invalid credentials | | --- | --- | --- | --- | | nothing (the default) | `401` `missing_credentials` | passes, user set | `401` | | `@Authenticate({ optional: true })` | passes, user `null` | passes, user set | `401` | | `@Public()` | passes, providers not called | passes, user `null` | passes, providers not called | The middle row matters for pages that serve guests but change for signed-in users. `@Public()` would hide the user even when one is signed in; `optional` runs the providers and only waives the requirement. Bad credentials still get a `401` on an optional route, so a client is told to refresh rather than silently treated as a guest. A stale or unknown session cookie, though, counts as no credentials rather than bad ones, so a browser holding an old cookie still reaches an optional route as a guest. ## Turning the default off `AuthenticationModule.forRoot({ globalGuard: false, ... })` skips the `APP_GUARD` registration. Routes then stay open until a controller or method opts in with `@UseGuards(AuthenticationGuard)`. Because the default guard is registered through `APP_GUARD`, it covers controllers in every module, including ones another team adds later, and in the request lifecycle it runs after middleware and before interceptors and pipes. Feature modules need no import of their own either: `isGlobal` defaults to `true`, so `AuthenticationContext` and the package's services can be injected anywhere once the root module imports `AuthenticationModule.forRoot()`. Most teams keep the default, because a forgotten decorator then fails closed (a `401` someone notices) instead of open (a data leak nobody notices). With `forRootAsync()`, `globalGuard` and `isGlobal` sit at the top level next to `useFactory`; returning them from the factory fails at startup, because they decide what the module registers. ## Common mistakes 1. Expecting routes to be open until each controller adds a guard: that is only true with `globalGuard: false`. 2. Reaching for `@Public()` on a route that needs to know who is calling; `@Authenticate({ optional: true })` is the decorator for that. 3. Using a hand-written `Public` decorator built with `SetMetadata`: this guard reads only the metadata that its own package's `@Public()` writes. 4. Expecting `403` for an anonymous caller. A missing user is `401`; the guard's `403` refusals, such as `email_unverified` on a `verifiedEmail` route, are for signed-in users who fail a route requirement. The health route is the canonical case: mark it `@Public()` and the probe gets its `200` without touching the session store.

  • What is the difference between @Public() and @Authenticate({ optional: true }) on a product catalog route?
    `@Public()` runs no credential provider, so even a signed-in customer arrives with a `null` `@CurrentUser()` and the route cannot personalise anything. `@Authenticate({ optional: true })` runs the providers: guests pass with `null`, a valid session yields the user, and credentials that are present but invalid still get a `401`. Choose `optional` whenever the response depends on who is signed in.
  • Can a @Public() controller still have one method that requires sign-in?
    Yes. Method options merge over class options field by field, and `@Authenticate()` sets the route back to non-public, so putting `@Authenticate()` on that method makes the guard require a user there while the rest of the controller stays open.

  • Routes stay open until each controller adds @UseGuards(AuthenticationGuard).
  • @Public() still runs the providers and only ignores their failures.
  • An anonymous request to a protected route gets 403 Forbidden.
  • A @Public() controller cannot contain a route that requires sign-in.
  • Any SetMetadata-based Public decorator is honoured by this guard.

Assumes NestJS 12: the first-party @nestjs/authentication package declares @nestjs/common and @nestjs/core 12 as peer dependencies and is taught by the v12 security docs.

open as a page

With NestJS 12's @nestjs/authentication, how does a credential provider join the global guard's chain, and which provider authenticates a request?

level: middleimportance: should knowfreq 25%

basics

~20 s

A credential provider is a singleton @Injectable() that calls registerProvider(this) on the injected AuthenticationRegistry in its constructor. The guard tries providers in ascending order; the first to return a user wins, and null passes to the next.

open as a page

In a NestJS 12 app on @nestjs/authentication, a credential provider's database lookup times out. What does the client receive, and why not 401?

level: seniorimportance: should knowfreq 18%

basics

~20 s

The guard catches only AuthenticationError; any other error from a provider is rethrown, so Nest answers 500 Internal server error. A 401 would wrongly tell clients their credentials are bad, prompting sign-outs and refresh storms during an outage.

open as a page

A NestJS 12 app on @nestjs/authentication signs every customer out on each deploy. What is missing, and what must its replacement session store guarantee?

level: seniorimportance: should knowfreq 20%

basics

~20 s

No SessionStore is registered, so sessions live in the in-memory default; the startup check only refuses that when NODE_ENV is production. Register a store with AuthenticationStorage.registerSource(), whose touchSession() is a conditional update and deleteSession() reports its row count.

open as a page

In NestJS 12's AuthenticationModule.forRoot(), why is session: { idleTtl: 3600 } a bug, and what else does the module reject at startup?

level: middleimportance: nice to knowfreq 15%

basics

~20 s

AuthenticationModule.forRoot() reads numeric lifetimes as milliseconds, so idleTtl: 3600 is 3.6 seconds: the module warns, then refuses to start because the one-minute touchInterval is not shorter. Unknown keys and features missing handlers also fail startup.

open as a page