skip to content

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%

answer

  1. which errors the guard catches
  2. null versus a thrown error
  3. an outage is not bad credentials
  4. AuthenticationError ends the chain

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.

solid answer

~50 s

NestJS 12's `AuthenticationGuard` walks the credential providers and distinguishes three outcomes: `null` means "not my credentials, try the next", a result with a user wins, and a thrown `AuthenticationError` means "my credentials, but invalid" and ends the chain with a refusal, `401` by default. Anything else, such as a database timeout, is rethrown, so Nest's exception layer answers `500` `Internal server error` unless your own filter maps it. That is deliberate: a `401` would make browser and mobile clients discard sessions or hammer the refresh endpoint during an outage. The session provider follows the same rules: a stale or unknown cookie is `null`, `validate()` returning `null` discards the session, and a store error propagates. A custom provider should return `null` for absent credentials, throw `AuthenticationError` only for its own invalid ones, and let infrastructure errors through.

go deeper

for a junior

Recall the three provider outcomes: a user, null for no credentials, and AuthenticationError for invalid ones; know that other errors become a 500.

for a middle

Explain how the guard walks the chain and why it rethrows non-authentication errors, and how the session provider handles stale cookies and deleted users.

for a senior

Diagnose a wave of 500s on protected routes with healthy public routes as a store outage, and show why mapping it to 401 would trigger mass sign-outs.

for a principal

Set the house rule for custom providers and exception filters, perhaps mapping store outages to 503, so outages never masquerade as authentication failures.

## Three outcomes a provider can report In NestJS 12's `@nestjs/authentication`, every credential provider's `authenticate(context)` has exactly three ways to finish, and the global `AuthenticationGuard` treats each differently: | Provider outcome | Meaning | Guard response | | --- | --- | --- | | resolves to a result with a `user` | "these credentials are mine and valid" | stops, records the user, request continues | | resolves to `null` | "no credentials I understand" | tries the next provider; if none is left, `401` `missing_credentials` (or a `null` user on optional routes) | | throws `AuthenticationError` | "these credentials are mine and invalid" | stops the chain, refuses with the error's status (`401` by default) and `code` | | throws anything else | an infrastructure failure | rethrows it, so Nest's exception layer answers | The last row is the answer to the timeout. The guard catches only `AuthenticationError`; anything else propagates with the comment in the package's source reading "a store outage is a 500, not a 401". Without an exception filter of your own, Nest's default handler logs the error and replies: ```json {"statusCode":500,"message":"Internal server error"} ``` ## Why a 500 is the honest answer A `401` tells the client **its credentials are bad**. A browser app reacts by discarding state and showing the sign-in page; a mobile client tries to refresh its token, fails again, and may sign the user out. If a database blip were reported as `401`, a few seconds of outage would sign out every active user and send a burst of sign-in attempts at a system that is already struggling. A `500` (or a `503` from your own filter) says "try again later", leaves credentials alone, and shows up on error-rate dashboards as the incident it is. The same rule applies on optional routes: a store outage there is still a `500`, not a silent downgrade to a guest. ## The session provider's own failure paths The built-in `SessionCookieProvider` maps the common cases onto those outcomes for you: - **No cookie, or a stale or unknown one**: `null`. Browsers keep sending old cookies, and optional routes should keep working, so this counts as no credentials rather than a `401` from the provider. - **A session cookie on a cross-origin `POST`, `PUT`, `PATCH` or `DELETE`**: ignored, so the request is anonymous; that is the package's CSRF defence on top of `SameSite=Lax`. - **`validate(session)` returns `null` or `undefined`** (the user was deleted or banned): the provider discards the session and returns `null`, so the user loses access on the next request rather than at expiry. - **`getSession()` or your repository throws**: the error propagates, and the client gets a `500`. Separately, `touchSession()`, which records activity, is best-effort: when it fails, the request still succeeds with the session as read, and a `session-touch-failed` event is published. ## Writing your own provider correctly ```typescript import { Injectable, type ExecutionContext } from '@nestjs/common'; import { AuthenticationError, AuthenticationProvider, AuthenticationRegistry } from '@nestjs/authentication'; import type { User } from '../users/user.js'; import { DeviceTokens } from './device-tokens.js'; @Injectable() export class DeviceTokenAuth extends AuthenticationProvider<User> { constructor(private readonly tokens: DeviceTokens, registry: AuthenticationRegistry) { super(); registry.registerProvider(this, { order: 2 }); } async authenticate(context: ExecutionContext) { const token = this.header(context, 'x-device-token'); if (!token) { return null; // not my credentials: let the next provider look } const user = await this.tokens.findUser(token); // a timeout here propagates as a 500 if (!user) { throw new AuthenticationError('Unknown device token', { code: 'unknown_device_token' }); } return { user }; } } ``` The rules this snippet follows: 1. Return `null` when the request carries nothing this provider understands, so other providers still get a turn. 2. Throw `AuthenticationError` only when the credentials are this provider's and fail verification; it ends the chain with a refusal. 3. Let infrastructure errors propagate. Wrapping a database error in `AuthenticationError` turns an outage into mass sign-outs. 4. Never swallow an error by returning `null`: that hides the outage and makes valid users look anonymous. ## Diagnosing it in production If signed-in clients get `500` on protected routes while `@Public()` routes stay healthy, the guard is the common factor: no provider runs on public routes, so they never touch the store. The Nest error log shows the original stack under the exceptions handler, and the session store's health is the place to look first.

  • What should a credential provider return when the request has no header it recognises?
    `null`. The guard then tries the next provider in the chain, and only when every provider has returned `null` does it answer `401` `missing_credentials`, or let the request through with a `null` user on an optional route. Throwing there would stop the chain and lock out callers that another provider could have authenticated.
  • On an @Authenticate({ optional: true }) route, does a provider's AuthenticationError still refuse the request?
    Yes. Optional only waives the requirement for callers with no credentials. Credentials that are present and invalid still get a `401`, so a client holding a bad credential is told to refresh or sign in again instead of being silently served as a guest.

A ticket gate that cannot reach its validation server shows 'gate out of order', not 'invalid ticket': the second message would send travellers to buy new tickets they don't need.

  • Any error thrown by a credential provider becomes a 401.
  • Wrap database errors in AuthenticationError so the client sees a clean 401.
  • Return null when the user lookup fails, to keep the request moving.
  • A stale session cookie makes the session provider answer 401 by itself.
  • Optional routes quietly serve a guest when the session store is down.

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.