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.
bun add @noctcore/auth-nestjs @noctcore/auth @nestjs/common @nestjs/core @nestjs/platform-expressNestJS 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.
The module
Section titled “The module”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 {}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
createAuthresult under theAUTHtoken, for your controllers and services; - registers
SessionGuardas a global guard; - applies
CsrfMiddlewareto every route; - provides
SessionCookies, which writes a new or ended session onto the response; - calls
auth.flush()inbeforeApplicationShutdown, so mail sends still in flight finish before your ownonApplicationShutdownhooks close the database and Redis connections. Nest runs it onapp.close(), and on SIGTERM oncemain.tscallsapp.enableShutdownHooks(). The wait is bounded by the module’sshutdownTimeoutoption (10 seconds by default), so a mailer whosesendnever settles cannot keep the app from closing: after that long, whatever is still running is logged through yourloggerasBackground 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.
The guard order
Section titled “The guard order”Nest runs middleware before guards, and the module uses that order on every request:
CsrfMiddlewarereads the session cookie through the core (readSessionToken, thenvalidateRequest) 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: theOriginmust be onallowedOrigins(orcrossSiteOrigins),Sec-Fetch-Sitemust saysame-originwhenever the browser sends it (orcross-sitefrom an origin oncrossSiteOrigins, for a desktop shell; see Cookies and desktop shells), and theX-CSRF-Tokenheader must match thecsrfcookie 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, with403and the body{"error":{"code":"forbidden"}}, whichever check failed. It never callsnext(err), so no exception filter can turn the refusal into a message that says more.SessionGuardfirst refuses, with the same403, 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 asPOST /apiundersetGlobalPrefix('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 with401and{"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.@TwoFactorEnrollment(): under the two-factor plugin’senforcement, a session past the grace window isenrollment-onlyand reaches only a route marked@TwoFactorEnrollment()(on the route or its controller); anything else answers403and{"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.@RequireRole()runs only after the session and the user are known. The module’srolesfunction 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.@RequireFreshAuth()asks the core’srequireFreshAuthwhether the session’s last password proof is withinfreshAuthAge. A route can pass a shortermaxAge, 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.
Background polls
Section titled “Background polls”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.
Signing in and out
Section titled “Signing in and out”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’sRequestMeta: the client IP through the trusted hops, the user agent and theOrigin. Pass it to every flow.SessionCookies.setwrites 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.signOutrevokes the session throughauth.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 arenullwhen nobody is signed in. Nothing in the module reads a user id from a header or the body.
Verification links
Section titled “Verification links”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.
Protected routes
Section titled “Protected routes”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.
The trust-proxy rule
Section titled “The trust-proxy rule”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 is0in development and refused in production, so a deploy that forgot it fails at boot instead of quietly trusting the wrong hops.trueis refused anywhere, and so is a count above 16 or anything that is neither a hop count nor a valid proxy list.TRUST_PROXYcan also list the proxies by address:loopback, 10.0.0.0/8trusts the loopback range and that subnet, withloopback,linklocalanduniquelocalexpanded to the ranges Express uses. ThenX-Forwarded-Foris 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’strust proxyto the same count or list, soreq.ipin your own code agrees with what the flows see. The module itself never readsreq.ip.clientIpHeader: 'cf-connecting-ip'(off by default) reads the client IP from a single-address header your edge sets. It needsTRUST_PROXY(ortrustedHops) 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; otherwiseX-Forwarded-Fordecides. 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’sreq.ipdoes not read it. See Trust proxy and client IPs.
The compile test
Section titled “The compile test”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.
Before going live
Section titled “Before going live”- Serve over HTTPS and leave
session.cookie.secureon. The CSRF cookies follow the session cookie:__Host-csrfand__Host-presessionwhen it is__Host-session, with theSameSitethatsession.cookie.sameSitegives the request’sOrigin. - Set
TRUST_PROXYto 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
403after 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.