Skip to content

Use with NestJS

@noctcore/auth-nestjs wires the core into a Nest app with the parts that are easy to get wrong done by default: every route needs a session unless it says otherwise, CSRF is checked before any guard, and the client IP behind a proxy cannot be left to chance. The core stays the same: the flows return AuthResult values and never throw HTTP errors, and the module only decides who gets through.

This guide builds on A Node server with Redis and Prisma: auth.ts and config.ts there are used as they are. A full app with its tests is in examples/nestjs in the repository.

Terminal window
bun add @noctcore/auth-nestjs @noctcore/auth @nestjs/common @nestjs/core @nestjs/platform-express

NestJS 11 and 12 are supported, on the Express platform, for HTTP controllers. GraphQL resolvers, WebSocket gateways and microservice handlers are not supported yet: the guard refuses them unless they are @Public(), so they never get through without a session check by accident. The package uses Nest’s legacy decorators, so set experimentalDecorators in your tsconfig.json, as every Nest project already does.

src/app.module.ts
import { Module } from '@nestjs/common';
import { AuthModule, trustedHopsFromEnv } from '@noctcore/auth-nestjs';
import { buildAuth } from '../node-server/auth';
import { config } from '../node-server/config';
import { AccountController } from './account.controller';
import { AuthController } from './auth.controller';
import { MAILER, MailModule } from './mail.module';
@Module({
imports: [
MailModule,
AuthModule.forRootAsync({
inject: [MAILER],
useFactory: (mailer: Parameters<typeof buildAuth>[0]) => ({
auth: buildAuth(mailer),
// Unset in production refuses to boot; "true" is refused anywhere.
trustedHops: trustedHopsFromEnv(process.env),
csrf: {
// Not the auth secret. Add the previous one after it during a rollover.
secrets: [config.csrfSecret],
allowedOrigins: [config.origin],
// A webhook that proves itself with a signature, not a cookie.
exempt: ['/webhooks/billing'],
},
// Read on every request that needs a role, with the user just loaded.
roles: (user) => ('role' in user ? [String(user.role)] : []),
}),
}),
],
controllers: [AuthController, AccountController],
})
export class AppModule {}
src/mail.module.ts
import { Global, Module } from '@nestjs/common';
import type { Mailer } from '@noctcore/auth';
export const MAILER = Symbol('mailer');
// Swap this for the queue from "Mail into your templates and queue".
const devMailer: Mailer = {
send: async (event) => void process.stdout.write(`[mail] ${event.type} to ${event.to}\n`),
};
@Global()
@Module({ providers: [{ provide: MAILER, useValue: devMailer }], exports: [MAILER] })
export class MailModule {}

AuthModule.forRootAsync (or forRoot with the options directly) does five things, and none of them can be switched off:

  • provides the createAuth result under the AUTH token, for your controllers and services;
  • registers SessionGuard as a global guard;
  • applies CsrfMiddleware to every route;
  • provides SessionCookies, which writes a new or ended session onto the response;
  • calls auth.flush() in beforeApplicationShutdown, so mail sends still in flight finish before your own onApplicationShutdown hooks close the database and Redis connections. Nest runs it on app.close(), and on SIGTERM once main.ts calls app.enableShutdownHooks(). The wait is bounded by the module’s shutdownTimeout option (10 seconds by default), so a mailer whose send never settles cannot keep the app from closing: after that long, whatever is still running is logged through your logger as Background flush stopped waiting, with the task labels, and abandoned.

The module is global, so feature modules get the guard, the decorators and AUTH without importing it again. Boot fails on a missing csrf, csrf.secrets or csrf.allowedOrigins, a CSRF secret shorter than 32 bytes, an empty origin allowlist, a crossSiteOrigins entry that is not one exact origin, a CSRF option of the wrong type (an allowSameSite that is not true or false, such as the string "false" from the environment, a single string where a list goes, a list with an empty slot such as [, '/webhook'], a headerName that is not a string, an exempt rule that is neither a path nor a RegExp), a roles option that is not a function, a hop count that is not a whole number from 0 to 16, a trusted proxy list with an entry that is not an address, a CIDR range or a preset, a range that trusts every address, or a clientIpHeader that is not a string, is not a header name or comes with a hop count instead of a proxy list. It also fails on a route whose decorators contradict each other: @Public() (on the route or its controller) together with @RequireRole() or @RequireFreshAuth(), or @RequireRole() without the roles option. The error names each route. Both this check and describeRoutes see the handlers a controller inherits from a base class or a mixin, the way Nest routes them: an override in the subclass replaces the base handler.

Nest runs middleware before guards, and the module uses that order on every request:

  1. CsrfMiddleware reads the session cookie through the core (readSessionToken, then validateRequest) and keeps the result for the rest of the request, so the session is validated once. On an unsafe method it runs the three checks from CSRF: the Origin must be on allowedOrigins (or crossSiteOrigins), Sec-Fetch-Site must say same-origin whenever the browser sends it (or cross-site from an origin on crossSiteOrigins, for a desktop shell; see Cookies and desktop shells), and the X-CSRF-Token header must match the csrf cookie and be signed for this session, or before sign-in for this browser’s pre-session id. A refusal is answered by the middleware itself, with 403 and the body {"error":{"code":"forbidden"}}, whichever check failed. It never calls next(err), so no exception filter can turn the refusal into a message that says more.
  2. SessionGuard first refuses, with the same 403, any unsafe request the middleware never saw. Which routes Nest hands to a middleware depends on its version and on the global prefix (Nest 11.0 to 11.2.7 and 12.0.0 to 12.1.2 skip the prefix root, such as POST /api under setGlobalPrefix('api'), and 11.0.0 also skips prefix-excluded routes), so the guard does not rely on that mapping: on those versions an unsafe request to such a route is refused even when it is legitimate, until you upgrade Nest. Then it refuses a route without a valid session with 401 and {"error":{"code":"session_expired"}}, unless the route or its controller carries @Public(). It loads the user from your user store on every request, so a deleted user is out at once.
  3. @TwoFactorEnrollment(): under the two-factor plugin’s enforcement, a session past the grace window is enrollment-only and reaches only a route marked @TwoFactorEnrollment() (on the route or its controller); anything else answers 403 and {"error":{"code":"two_factor_enrollment_required"}}. The standing is read from this request’s validation, so it follows the policy without a new sign-in. See Enforcement with a grace period.
  4. @RequireRole() runs only after the session and the user are known. The module’s roles function is called with the user just loaded, on every request, so a role taken away stops working on the next request. No role is ever copied into the cookie or the session.
  5. @RequireFreshAuth() asks the core’s requireFreshAuth whether the session’s last password proof is within freshAuthAge. A route can pass a shorter maxAge, never a longer one.

@Public() lets a request through without a session, and skips steps 3 to 5, only on a route with no role or fresh-auth requirement. The guard still resolves a session the request carries, and its user, on a public route, so @CurrentSession() and @CurrentUser() name the caller when there is one: flows that refuse another account’s session, such as an email verification link, rely on that. A store failure in the middleware or the guard is answered with a fixed 500 and logged by its error name only, so no message with a session key reaches your logs.

Safe methods (GET, HEAD, OPTIONS) skip the CSRF check, never the session check. On a safe request the middleware also hands out what the page needs for its next unsafe one: a pre-session id when the browser has neither a session nor an id, and a csrf cookie when the one it holds is missing or bound to something else. A session cookie the core refused for good is cleared on the same response (clearsSessionCookie); one another request may still be adopting from your own store is kept (see Switching from your own sessions).

csrf.exempt lists paths that skip the middleware entirely, such as a webhook that proves itself with a signature. Nothing is minted on an exempt path, and the guard still applies to it: mark the webhook route @Public() as well, and check its signature in the handler.

Every request that carries a session counts as activity and refreshes its last-active time, at most once per touchInterval. For requests the page makes on its own, such as a poll on a timer, pass touch a predicate that returns false, so an idle session still expires while only those arrive (see Background polls):

AuthModule.forRoot({
// ...
touch: (request) => !(request.method === 'GET' && request.path === '/api/notifications/count'),
});

The predicate sees the method, the path (a global prefix included, no query string, and not normalised: a trailing slash or another case is a different path, so lower-case it and strip a trailing slash before comparing, or the poll touches) and the headers, and runs before the middleware validates the session. Under nestjs-trpc the tRPC context validates the same request again with its own touch, and a poll stays passive only when both say so (see Use with tRPC). It cannot read route decorators: the middleware validates the session before Nest picks a handler. A passive request is still answered with its session, and the CSRF checks and the guard’s decisions do not change. touch: false touches on no request; the default, true, on every one.

src/auth.controller.ts
import { Body, Controller, Get, HttpException, Inject, Post, Req, Res } from '@nestjs/common';
import {
toPublicError,
type AuthFailure,
type AuthUser,
type RequestMeta,
type StoredSession,
} from '@noctcore/auth';
import {
AUTH,
AuthMeta,
CurrentSession,
CurrentUser,
Public,
SessionCookies,
} from '@noctcore/auth-nestjs';
import type { AppAuth } from '../node-server/auth';
// Only the public code goes over the wire; the reason is for audit rows.
function refusal(result: AuthFailure): HttpException {
const error = toPublicError(result);
return new HttpException({ error }, error.code === 'rate_limited' ? 429 : 401);
}
@Controller('auth')
export class AuthController {
constructor(
@Inject(AUTH) private readonly auth: AppAuth,
@Inject(SessionCookies) private readonly cookies: SessionCookies,
) {}
// The page's first call. Like every GET, it also hands out the CSRF cookie.
@Public()
@Get('session')
session(@CurrentUser() user: AuthUser | null) {
return { user: user && { id: user.id, email: user.email } };
}
@Public()
@Post('login')
async login(
@Body() body: { email: string; password: string; rememberMe?: boolean },
@AuthMeta() meta: RequestMeta,
@Req() req: { headers: { cookie?: string } },
@Res({ passthrough: true }) res: unknown,
) {
const result = await this.auth.login({
email: body.email,
password: body.password,
rememberMe: body.rememberMe === true,
deviceToken: this.auth.readDeviceToken(req.headers.cookie),
meta,
});
if (!result.ok) throw refusal(result);
if (result.value.kind === 'challenge') return { methods: result.value.methods };
// Session cookie, device cookie and a CSRF token bound to the new session.
return this.cookies.set(res, result.value.session);
}
// The page the mail links to keeps the token in its fragment, does nothing
// on load, and POSTs it here when the user clicks Confirm: a mail scanner
// that fetches the link never verifies anything. The guard still resolves
// the session on a public route, so a link for another account is refused.
@Public()
@Post('verify-email-link')
async verifyEmailLink(
@Body() body: { token: string },
@CurrentSession() session: StoredSession<Record<string, never>> | null,
@AuthMeta() meta: RequestMeta,
@Res({ passthrough: true }) res: unknown,
) {
const result = await this.auth.verifyEmailLink({ token: body.token, session, meta });
if (!result.ok) throw refusal(result);
// Signed in as this account: the session was re-issued. Otherwise nobody
// is signed in (with linkWithoutSession) and the page asks them to sign in.
const issued = result.value.session;
return issued ? { verified: true, ...this.cookies.set(res, issued) } : { verified: true };
}
@Public()
@Post('logout')
logout(@Req() req: unknown, @Res({ passthrough: true }) res: unknown) {
return this.cookies.signOut(req, res);
}
}
  • @AuthMeta() is the request’s RequestMeta: the client IP through the trusted hops, the user agent and the Origin. Pass it to every flow.
  • SessionCookies.set writes the session cookie, the trusted-device cookie and a CSRF cookie bound to the new session, and returns the token for the response body. Every flow that issues a session goes through it: sign-in, re-authentication, a password change, revoking the other sessions, a verified address. Each one rotates the session, so each one needs a new CSRF token.
  • SessionCookies.signOut revokes the session through auth.logout, clears its cookie and starts a fresh pre-session with its own token.
  • @CurrentUser() and @CurrentSession() read what the guard resolved from the stored session. On a public route they are null when nobody is signed in. Nothing in the module reads a user id from a header or the body.

verifyEmailLink above is a @Public() POST. The guard still resolves the session on a public route, so @CurrentSession() is the caller’s session when there is one and null otherwise; pass it as it is. A link for one account opened while signed in as another is then refused (401, session_expired) and stays usable for its owner. By default a link opened with no session is refused the same way; with emailVerification.linkWithoutSession on it verifies the address and signs nobody in.

Never verify on a GET or when the page loads: mail scanners fetch links in mail, and with linkWithoutSession on a fetch that reaches this route verifies the account. Put the token in the URL fragment (urls.verifyEmail: (token) => `${origin}/verify#${token}` ), show a Confirm button, and POST the token on the click. See Email verification for the trade-off.

src/account.controller.ts
import { Body, Controller, Get, HttpException, Inject, Post, Res } from '@nestjs/common';
import { toPublicError, type AuthUser, type RequestMeta, type StoredSession } from '@noctcore/auth';
import {
AUTH,
AuthMeta,
CurrentSession,
CurrentUser,
RequireFreshAuth,
RequireRole,
SessionCookies,
} from '@noctcore/auth-nestjs';
import type { AppAuth } from '../node-server/auth';
type Session = StoredSession<Record<string, never>>;
// No @Public(): every route here needs a session.
@Controller('account')
export class AccountController {
constructor(
@Inject(AUTH) private readonly auth: AppAuth,
@Inject(SessionCookies) private readonly cookies: SessionCookies,
) {}
@Get('me')
me(@CurrentUser() user: AuthUser) {
return { id: user.id, email: user.email };
}
// Each session is named by its public handle, never its store key.
@Get('sessions')
async sessions(@CurrentSession() session: Session) {
return { sessions: await this.auth.sessions.list(session) };
}
// Signs out one device by the handle the list showed. Another device needs a
// fresh password proof by default; a handle that names none of the caller's
// sessions answers { revoked: false }.
@Post('sessions/revoke')
async revokeSession(
@Body() body: { handle: string },
@CurrentSession() session: Session,
@AuthMeta() meta: RequestMeta,
) {
const result = await this.auth.sessions.revoke({ session, handle: body.handle, meta });
if (!result.ok) throw new HttpException({ error: toPublicError(result) }, 403);
// result.value.sessionId is the store key: keep it on the server.
return { revoked: result.value.revoked };
}
// Proving the password again rotates the session.
@Post('reauthenticate')
async reauthenticate(
@Body() body: { password: string },
@CurrentSession() session: Session,
@AuthMeta() meta: RequestMeta,
@Res({ passthrough: true }) res: unknown,
) {
const result = await this.auth.reauthenticate({ session, password: body.password, meta });
if (!result.ok) throw new HttpException({ error: toPublicError(result) }, 401);
return this.cookies.set(res, result.value);
}
// A recent password proof, and at most 5 minutes old here.
@RequireFreshAuth('5m')
@Post('delete')
async remove(@CurrentUser() user: AuthUser) {
return { scheduled: user.id };
}
@RequireRole('admin')
@Get('audit')
audit() {
return { rows: [] };
}
}

The sessions routes name each session by its public handle, which is what sessions.revoke takes; a store key never reaches the response. A handle that names none of the caller’s sessions, another user’s included, answers { revoked: false }. See Session handles.

@RequireRole('a', 'b') accepts a user with either role. On a controller and a handler both, each list must be satisfied.

src/main.ts
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { configureTrustProxy } from '@noctcore/auth-nestjs';
import { AppModule } from './app.module';
const app = await NestFactory.create(AppModule);
// Express's req.ip now counts the same hops as the auth flows.
configureTrustProxy(app, process.env);
app.enableShutdownHooks();
await app.listen(Number(process.env.PORT ?? 3000));

TRUST_PROXY is the number of reverse proxies in front of the app. X-Forwarded-For is written by the client up to the first proxy you run, so the module trusts exactly that many hops, counted from the right, the same rule as the core’s clientIp. Trusting everything lets a client choose its own IP and its own rate-limit bucket; trusting nothing behind a proxy puts every client in one bucket, where one attacker blocks logins for everyone.

  • trustedHopsFromEnv(process.env) reads it for the module. Unset is 0 in development and refused in production, so a deploy that forgot it fails at boot instead of quietly trusting the wrong hops. true is refused anywhere, and so is a count above 16 or anything that is neither a hop count nor a valid proxy list.
  • TRUST_PROXY can also list the proxies by address: loopback, 10.0.0.0/8 trusts the loopback range and that subnet, with loopback, linklocal and uniquelocal expanded to the ranges Express uses. Then X-Forwarded-For is read only when the socket address is inside the list, so a client that reaches the app directly cannot pose as a proxy. An unknown name or a malformed range is refused at boot.
  • configureTrustProxy(app, process.env) sets Express’s trust proxy to the same count or list, so req.ip in your own code agrees with what the flows see. The module itself never reads req.ip.
  • clientIpHeader: 'cf-connecting-ip' (off by default) reads the client IP from a single-address header your edge sets. It needs TRUST_PROXY (or trustedHops) as a proxy list and is refused at boot with a hop count, which never checks the socket address. It is read only when the socket address is inside the list and the value is exactly one IP; otherwise X-Forwarded-For decides. The list must name the edge itself, or hops that accept traffic only from the edge: someone who can reach a listed internal load balancer directly can set the header. Name only a header your edge always overwrites. Express’s req.ip does not read it. See Trust proxy and client IPs.
test/app.test.ts
import 'reflect-metadata';
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { Test } from '@nestjs/testing';
import { describeRoutes } from '@noctcore/auth-nestjs';
import request from 'supertest';
import { AppModule } from './app.module';
// The routes meant to be reachable without a session.
const PUBLIC_ROUTES = ['GET /auth/session', 'POST /auth/login', 'POST /auth/logout'];
test('the whole app boots, and only the listed routes are open', async () => {
// Fails on a provider Nest cannot resolve, here instead of at deploy.
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
const app = moduleRef.createNestApplication();
await app.init();
const routes = describeRoutes(app);
const open = routes.filter((r) => r.public).map((r) => `${r.method} ${r.path}`);
assert.deepEqual(open.sort(), [...PUBLIC_ROUTES].sort());
for (const route of routes.filter((r) => !r.public && r.method === 'GET')) {
const answer = await request(app.getHttpServer()).get(route.path);
assert.equal(answer.status, 401, `${route.method} ${route.path}`);
}
await app.close();
});

Boot the whole AppModule in a test. A provider Nest cannot resolve fails there, in CI, instead of on the first deploy. describeRoutes(app) lists every controller route with the rule the guard will apply (public or not, its roles, fresh auth), so the test can pin the list of open routes: opening a new one shows up in the diff as a change to that list. examples/nestjs walks the unsafe routes too, after a page visit for the CSRF token, and runs the same app end to end on Redis and PostgreSQL.

  • Serve over HTTPS and leave session.cookie.secure on. The CSRF cookies follow the session cookie: __Host-csrf and __Host-presession when it is __Host-session, with the SameSite that session.cookie.sameSite gives the request’s Origin.
  • Set TRUST_PROXY to the number of proxies you actually run, or to their addresses.
  • Keep the CSRF secret separate from the auth secret; during a rollover, list the new one first and the old one after it. Each safe request replaces a token signed by the old secret with one under the new secret. A page that kept the old token in memory gets one 403 after another request replaced the cookie, and should read the token again (or retry once after a safe request). Remove the old secret once your clients have made a safe request since the deploy (keeping it for one session idle timeout covers every signed-in client); a client that has not gets one 403, and a new token on its next safe request.
  • Fastify is not supported yet. The middleware and the cookies work on the raw Node request and response, but only Express is tested.
  • If you use a global prefix, run Nest 11.2.8 or later (or 12.1.3 or later), so the middleware reaches the prefix root and excluded routes and the guard’s safety net never has to refuse a legitimate request.