Skip to content

A Node server with Redis and Prisma

This guide

You build

A node:http server that checks its configuration at startup, reads the client IP behind your proxies, runs all three CSRF checks and serves sign-up, sign-in, verification, reset and sign-out.

You need first

Getting started for the install and the Prisma schema, a Postgres database, and a Redis that runs with maxmemory-policy noeviction.

It works when

A write without the CSRF header is refused with 403 and the same write with it is accepted; examples/basic runs the whole flow in an end-to-end test.

Getting started ends with a server that signs people in. This guide adds what it left out: configuration read and checked at startup, the client IP behind a proxy, the CSRF token layer, email verification, password reset and a session-aware route. The same pieces, with an end-to-end test, are in examples/basic in the repository.

The server is six files. Install and the Prisma schema are the same as in Getting started.

Every request reads the client IP, validates the session and checks CSRF before any route runs; of the three, only the CSRF check turns a request away. The routes and the session check go through one auth instance, which holds the stores, the mailer and the logger.

One request runs through handle() in server.ts in four steps. clientIp reads the client address, trusting as many proxies as trustedHops from config.ts says. validateRequest asks the auth instance for the session, or null. csrfAllowed, in csrf.ts, runs the three CSRF checks on every unsafe method and refuses a failing request with a 403 forbidden. Then the route runs an auth flow and http.ts sends the response. The auth instance, built by buildAuth(mailer) with createAuth in auth.ts, holds four things: the Redis stores (redisStores) for sessions and counters, the Prisma stores (prismaStores) on Postgres for users and tokens, the mailer it is given as a parameter, and a logger for warnings.

Text version
  1. Read every setting once, at startup, and fail before the server listens. The two secrets must differ: the auth secret derives the keys for codes and device cookies, the CSRF secret signs CSRF tokens only.

    src/config.ts
    import { parseTrustProxy, resolveTrustedProxies } from '@noctcore/auth';
    function required(name: string): string {
    const value = process.env[name];
    if (!value) throw new Error(`Set ${name}`);
    return value;
    }
    // parseTrustProxy refuses "true" (any client could pick its IP). A hop count
    // stays a number; an address list ("loopback, 10.0.0.0/8") is checked and its
    // presets expanded, so a typo fails here instead of trusting nothing.
    const trustProxy = parseTrustProxy(process.env.TRUST_PROXY);
    export const config = {
    /** At least 32 random bytes: `openssl rand -hex 32`. */
    authSecret: required('AUTH_SECRET'),
    /** A different 32 bytes or more, for CSRF tokens only. */
    csrfSecret: required('CSRF_SECRET'),
    databaseUrl: required('DATABASE_URL'),
    redisUrl: required('REDIS_URL'),
    /** The app's own origin, for example https://app.example. */
    origin: required('APP_ORIGIN'),
    /** How many reverse proxies sit in front of this server, or their addresses. */
    trustedHops:
    trustProxy === false
    ? 0
    : typeof trustProxy === 'string'
    ? resolveTrustedProxies(trustProxy)
    : trustProxy,
    /** False only for plain-HTTP local development. */
    secureCookies: process.env.NODE_ENV === 'production',
    };
    if (config.authSecret === config.csrfSecret)
    throw new Error('Use separate secrets for auth and CSRF');

    TRUST_PROXY is the number of reverse proxies in front of the server. Every per-IP limit and audit row reads the client IP, and X-Forwarded-For is written by the client up to the first proxy you run, so the server trusts exactly that many hops from the right.

    TRUST_PROXY What the server trusts
    unset, empty or false No proxy: trustedHops is 0.
    a hop count Exactly that many hops from the right of X-Forwarded-For.
    a list of proxies (loopback, 10.0.0.0/8) resolveTrustedProxies checks the list and expands the presets to the ranges Express uses; clientIp then reads X-Forwarded-For only from a socket address inside it.
    true Refused by parseTrustProxy.
  2. src/db.ts
    import { PrismaPg } from '@prisma/adapter-pg';
    import { config } from './config';
    import { PrismaClient } from './generated/prisma/client';
    export const prisma = new PrismaClient({
    adapter: new PrismaPg({ connectionString: config.databaseUrl }),
    });
  3. src/auth.ts
    import { createAuth, pwnedPasswords, type Logger, type Mailer } from '@noctcore/auth';
    import { argon2id } from '@noctcore/auth/argon2';
    import { prismaStores } from '@noctcore/auth-prisma';
    import { redisStores } from '@noctcore/auth-redis';
    import { Redis } from 'ioredis';
    import { config } from './config';
    import { prisma } from './db';
    // The longest a session can live. The Redis store must guard at least this
    // long, so the same value goes to both.
    const REMEMBER_ME_TTL = '30d';
    // Bounded, so an outage fails requests in milliseconds, not after about 73 s.
    export const redis = new Redis(config.redisUrl, {
    maxRetriesPerRequest: 1,
    enableOfflineQueue: false,
    connectTimeout: 2_000,
    commandTimeout: 1_000,
    retryStrategy: (attempt) => Math.min(attempt * 200, 2_000),
    });
    redis.on('error', (error) => process.stderr.write(`redis: ${error.name}\n`));
    // With the offline queue off, a command sent before the connection is up is
    // rejected, so wait for it (bounded) before serving.
    await new Promise<void>((resolve, reject) => {
    const timer = setTimeout(
    () => reject(new Error('Redis was not ready within 10 seconds')),
    10_000,
    );
    redis.once('ready', () => {
    clearTimeout(timer);
    resolve();
    });
    });
    const { sessions, counters } = redisStores(redis, {
    prefix: 'auth:',
    maxSessionTtl: REMEMBER_ME_TTL,
    });
    export const stores = {
    ...prismaStores({ delegate: prisma.user, tokenDelegate: prisma.authToken }),
    sessions,
    counters,
    };
    // What the package cannot return goes here: a breach check that failed, an
    // audit sink or mailer that threw. Never secrets; user ids at most.
    const logger: Logger = {
    warn: (message, context) =>
    process.stderr.write(`${JSON.stringify({ level: 'warn', message, ...context })}\n`),
    error: (message, context) =>
    process.stderr.write(`${JSON.stringify({ level: 'error', message, ...context })}\n`),
    };
    export function buildAuth(mailer: Mailer) {
    return createAuth({
    stores,
    password: { hasher: argon2id(), breachCheck: pwnedPasswords() },
    session: {
    rememberMeTtl: REMEMBER_ME_TTL,
    cookie: { secure: config.secureCookies },
    },
    secret: config.authSecret,
    urls: {
    resetPassword: (token) => `${config.origin}/reset-password#${token}`,
    // The link the old address gets after an email change, to undo it.
    revertEmailChange: (token) => `${config.origin}/email/revert#${token}`,
    },
    mailer,
    logger,
    });
    }
    export type AppAuth = ReturnType<typeof buildAuth>;
    • One TTL in two places. The Redis store guards a user’s revocation epoch for maxSessionTtl, and createAuth refuses a session that could outlive it. Keeping rememberMeTtl and maxSessionTtl in one constant makes the pair impossible to get out of step.
    • A bounded Redis client. With ioredis’s defaults a Redis outage holds every request for about 73 seconds (20 retries per command), and the waiting requests pile up until the app is down too. maxRetriesPerRequest: 1 ends a command after one reconnect, enableOfflineQueue: false rejects commands at once while the client is not connected (the snippet waits, bounded, for its ready event before it serves), connectTimeout and commandTimeout cover a network that drops packets instead of refusing them, and retryStrategy only sets how often the client reconnects in the background. The client reconnects on its own when Redis comes back, with no restart, because the strategy never returns null; returning null ends reconnection for good. Size commandTimeout above your Redis p99 (a loaded instance, a long script): a command that timed out may still have run on the server, and the library fails closed on the rejection, so that is safe. During an outage the store call rejects with the ioredis error and the core does not catch it, so a flow such as validateRequest or sign-in rejects instead of returning a result: nothing is let through on a failed check. @noctcore/auth-nestjs answers 500 and @noctcore/auth-trpc an internal error; in your own handler, catch the rejection, answer 503 and log only error.name.
    • A logger. Without one, the package’s warnings (a breach check that could not run, a mailer that threw) go nowhere.
    • The mailer is a parameter so the server can pass a development mailer and production a queue; see Mail into your templates and queue.
  4. The session cookie is SameSite=Lax, which stops most cross-site requests on its own. This module adds the three checks CSRF describes, for every unsafe method:

    1. the Origin header must be the app’s own;
    2. Sec-Fetch-Site must say same-origin whenever the browser sends it;
    3. a signed double-submit token: the page reads the csrf cookie and echoes it in an X-CSRF-Token header, and the token’s HMAC binds it to the current session, or, before sign-in, to a random id this browser alone holds in an HttpOnly cookie.
    src/csrf.ts
    import { randomBytes } from 'node:crypto';
    import {
    createCsrfToken,
    verifyCsrfToken,
    verifyFetchSite,
    verifyRequestOrigin,
    type CookieSpec,
    type StoredSession,
    } from '@noctcore/auth';
    import { config } from './config';
    const secret = new TextEncoder().encode(config.csrfSecret);
    const csrfCookie = config.secureCookies ? '__Host-csrf' : 'csrf';
    const preSessionCookie = config.secureCookies ? '__Host-presession' : 'presession';
    const PRE_SESSION = /^[0-9a-f]{32}$/u;
    /** Signed in: bind to the session. Signed out: bind to this browser's own random id. */
    function binding(session: StoredSession | null, preSession: string | null): string | null {
    if (session) return `session:${session.id}`;
    return preSession ? `pre:${preSession}` : null;
    }
    /** The valid pre-session id from the request's cookies, if any. */
    export function readPreSession(cookies: Map<string, string>): string | null {
    const value = cookies.get(preSessionCookie);
    return value && PRE_SESSION.test(value) ? value : null;
    }
    /** A fresh pre-session id for a signed-out browser, in an HttpOnly cookie. */
    export function newPreSession(): { id: string; cookie: CookieSpec } {
    const id = randomBytes(16).toString('hex');
    const attributes = {
    httpOnly: true,
    secure: config.secureCookies,
    sameSite: 'lax',
    path: '/',
    } as const;
    return { id, cookie: { name: preSessionCookie, value: id, attributes } };
    }
    /** A token for the current binding: the page reads the cookie and echoes it in X-CSRF-Token. */
    export function issueCsrfToken(
    session: StoredSession | null,
    preSession: string | null,
    ): { token: string; cookie: CookieSpec } {
    const token = createCsrfToken(secret, binding(session, preSession) ?? '');
    const attributes = {
    httpOnly: false,
    secure: config.secureCookies,
    sameSite: 'lax',
    path: '/',
    } as const;
    return { token, cookie: { name: csrfCookie, value: token, attributes } };
    }
    /** All three layers, for every unsafe method. */
    export function csrfAllowed(input: {
    method: string;
    origin: string | undefined;
    secFetchSite: string | undefined;
    headerToken: string | undefined;
    cookies: Map<string, string>;
    session: StoredSession | null;
    }): boolean {
    const { method } = input;
    if (method === 'GET' || method === 'HEAD') return true;
    const originOk = verifyRequestOrigin({
    method,
    origin: input.origin,
    allowedOrigins: [config.origin],
    });
    // Sec-Fetch-Site whenever the browser sends it; the Origin check covers older browsers.
    const siteOk =
    input.secFetchSite === undefined ||
    verifyFetchSite({ method, secFetchSite: input.secFetchSite });
    const bound = binding(input.session, readPreSession(input.cookies));
    const tokenOk =
    bound !== null &&
    verifyCsrfToken({
    cookieToken: input.cookies.get(csrfCookie),
    headerToken: input.headerToken,
    binding: bound,
    secrets: [secret],
    });
    return originOk && siteOk && tokenOk;
    }

    Every change of session changes the binding, so the server hands out a new token whenever it sets a session cookie and when it signs out.

  5. The flows return AuthResult values. A refusal has a public code and an internal reason; only toPublicError(result) goes over the wire, because the reason can tell a wrong password from an unknown account.

    src/http.ts
    import type { IncomingMessage, ServerResponse } from 'node:http';
    import { serializeCookie, toPublicError, type AuthFailure, type CookieSpec } from '@noctcore/auth';
    // Every code the flows can return maps to a status. Anything else is a 400.
    const STATUS: Partial<Record<string, number>> = {
    invalid_credentials: 401,
    session_expired: 401,
    rate_limited: 429,
    fresh_auth_required: 403,
    forbidden: 403,
    captcha_unavailable: 503,
    };
    export function send(
    res: ServerResponse,
    status: number,
    body: unknown,
    cookies: readonly CookieSpec[] = [],
    headers: Record<string, string> = {},
    ): void {
    res.writeHead(status, {
    'content-type': 'application/json',
    'cache-control': 'no-store',
    // Reset and verification links carry their token in the URL.
    'referrer-policy': 'no-referrer',
    ...headers,
    ...(cookies.length > 0 ? { 'set-cookie': cookies.map(serializeCookie) } : {}),
    });
    res.end(JSON.stringify(body));
    }
    /** Sends only the public part of a refusal; `reason` stays on the server. */
    export function failure(res: ServerResponse, result: AuthFailure): void {
    const error = toPublicError(result);
    const headers: Record<string, string> = error.retryAfterSeconds
    ? { 'retry-after': String(error.retryAfterSeconds) }
    : {};
    send(res, STATUS[error.code] ?? 400, { error }, [], headers);
    }
    export function header(req: IncomingMessage, name: string): string | undefined {
    const value = req.headers[name];
    return Array.isArray(value) ? value[0] : value;
    }
    /** A JSON object body of at most 16 KiB, else an empty object. */
    export async function readJson(req: IncomingMessage): Promise<Record<string, unknown>> {
    if (header(req, 'content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')
    return {};
    const chunks: Buffer[] = [];
    let size = 0;
    for await (const chunk of req as AsyncIterable<Buffer>) {
    size += chunk.length;
    if (size > 16_384) return {};
    chunks.push(chunk);
    }
    try {
    const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
    return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
    } catch {
    return {};
    }
    }
    export function str(value: unknown): string {
    return typeof value === 'string' ? value : '';
    }
  6. src/server.ts
    import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
    import {
    clientIp,
    parseCookieHeader,
    type CookieSpec,
    type RequestMeta,
    type StoredSession,
    } from '@noctcore/auth';
    import { buildAuth, stores } from './auth';
    import { config } from './config';
    import { csrfAllowed, issueCsrfToken, newPreSession, readPreSession } from './csrf';
    import { failure, header, readJson, send, str } from './http';
    // Printing mail is for development; the mail guide replaces this with a queue.
    const auth = buildAuth({
    async send(event) {
    process.stdout.write(`[mail] ${event.type} to ${event.to}\n`);
    },
    });
    async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
    const method = req.method ?? 'GET';
    const route = `${method} ${new URL(req.url ?? '/', config.origin).pathname}`;
    const cookies = parseCookieHeader(req.headers.cookie);
    const meta: RequestMeta = {
    ip:
    clientIp({
    remoteAddress: req.socket.remoteAddress,
    forwardedFor: req.headers['x-forwarded-for'],
    trustedHops: config.trustedHops,
    }) ?? 'unknown',
    userAgent: req.headers['user-agent'],
    origin: req.headers.origin,
    };
    // One validation per request; it also slides the idle timeout.
    const token = cookies.get(auth.cookieName) ?? null;
    const validated = token ? await auth.validateRequest({ token, meta }) : null;
    const session = validated?.ok ? validated.value : null;
    const csrfOk = csrfAllowed({
    method,
    origin: req.headers.origin,
    secFetchSite: header(req, 'sec-fetch-site'),
    headerToken: header(req, 'x-csrf-token'),
    cookies,
    session,
    });
    if (!csrfOk) return send(res, 403, { error: { code: 'forbidden' } });
    const body = method === 'POST' ? await readJson(req) : {};
    switch (route) {
    case 'GET /api/csrf': {
    const preSession = readPreSession(cookies);
    const fresh = session || preSession ? null : newPreSession();
    const csrf = issueCsrfToken(session, preSession ?? fresh?.id ?? null);
    return send(
    res,
    200,
    { csrfToken: csrf.token },
    fresh ? [fresh.cookie, csrf.cookie] : [csrf.cookie],
    );
    }
    case 'POST /api/register': {
    const result = await auth.register({
    email: str(body.email),
    password: str(body.password),
    meta,
    });
    if (!result.ok) return failure(res, result);
    return send(res, 202, { status: 'check-your-email' });
    }
    case 'POST /api/login': {
    const result = await auth.login({
    email: str(body.email),
    password: str(body.password),
    rememberMe: body.rememberMe === true,
    deviceToken: auth.readDeviceToken(req.headers.cookie),
    meta,
    });
    if (!result.ok) return failure(res, result);
    if (result.value.kind === 'challenge') {
    return send(res, 200, { challenge: result.value.challenge, methods: result.value.methods });
    }
    const issued = result.value.session;
    return signedIn(res, issued.session, [issued.cookie, issued.deviceCookie]);
    }
    case 'POST /api/verify-email': {
    if (!session)
    return failure(res, { ok: false, code: 'session_expired', reason: 'no_session' });
    const result = await auth.verifyEmailCode({ session, code: str(body.code), meta });
    if (!result.ok) return failure(res, result);
    // Verifying can rotate the session: then the CSRF binding changes too.
    const rotated = result.value.session;
    if (!rotated) return send(res, 200, { verified: true });
    return signedIn(res, rotated.session, [rotated.cookie, rotated.deviceCookie], {
    verified: true,
    });
    }
    case 'POST /api/password-reset/request': {
    const result = await auth.requestPasswordReset({ email: str(body.email), meta });
    if (!result.ok) return failure(res, result);
    // The same answer for every address; the mail, if any, is sent off this path.
    return send(res, 202, { status: 'check-your-email' });
    }
    case 'POST /api/password-reset': {
    const result = await auth.resetPassword({
    token: str(body.token),
    password: str(body.password),
    meta,
    });
    if (!result.ok) return failure(res, result);
    return send(res, 200, { status: 'password-changed' });
    }
    case 'GET /api/me': {
    if (!session)
    return failure(res, { ok: false, code: 'session_expired', reason: 'no_session' });
    return send(res, 200, { user: await stores.users.findById(session.userId) });
    }
    case 'POST /api/logout': {
    const { cookie } = await auth.logout({ token, meta });
    // Signed out again: a new pre-session id and a token bound to it.
    const fresh = newPreSession();
    const csrf = issueCsrfToken(null, fresh.id);
    return send(res, 200, { csrfToken: csrf.token }, [cookie, fresh.cookie, csrf.cookie]);
    }
    default:
    return send(res, 404, { error: { code: 'not_found' } });
    }
    }
    /** A new session means a new CSRF binding: hand out both. */
    function signedIn(
    res: ServerResponse,
    session: StoredSession,
    cookies: CookieSpec[],
    extra: object = {},
    ): void {
    const csrf = issueCsrfToken(session, null);
    send(res, 200, { ...extra, csrfToken: csrf.token }, [...cookies, csrf.cookie]);
    }
    createServer((req, res) => {
    handle(req, res).catch((error: unknown) => {
    process.stderr.write(
    `request failed: ${error instanceof Error ? error.stack : String(error)}\n`,
    );
    if (!res.headersSent) send(res, 500, { error: { code: 'internal' } });
    });
    }).listen(3000);
    • One validation per request. validateRequest checks the session, slides its idle timeout (at most one write a minute) and refuses a revoked one. Pass touch: false for traffic the client makes on its own, such as polls, so they do not keep a session alive.
    • Answers that reveal nothing. Register and the reset request answer 202 whatever the address. The reset request does no per-account work on the response path: the lookup and the mail run in a job, detached in-process here, on your queue once you set passwordReset.enqueue.
    • The reset link points at /reset-password#<token>. The fragment never reaches a server log or a Referer; the page reads it and posts it with the new password. A completed reset revokes every session and lifts a lockout.
    • Verification can rotate the session, because verifying an address signs out the account’s other sessions; when it does, the response carries the new session cookie and a new CSRF token.
    • A devices page lists auth.sessions.list(session) and signs one out with auth.sessions.revoke({ session, handle, meta }). Each entry carries a public handle, never the session’s store key; see Session handles. examples/basic has both routes.
    • Sign-in sets the device cookie (__Host-device) beside the session. It matters only while the account is locked, where it lets the owner’s correct password through; see Brute force and lockout.
  • Serve over HTTPS and leave session.cookie.secure on (it is on whenever NODE_ENV is production here).
  • Set TRUST_PROXY to the number of proxies you actually run, or to their addresses.
  • Point the mailer at a queue.
  • Add an audit sink if you need a record of sign-ins and refusals.
  • Delete expired tokens now and then (expiresAt is indexed): prisma.authToken.deleteMany({ where: { expiresAt: { lt: new Date() } } }).

Start the server with APP_ORIGIN=http://localhost:3000 and NODE_ENV unset, so the cookies are the plain-HTTP csrf and presession ones. Then walk the CSRF layer by hand, keeping cookies in a jar:

Terminal window
# A token for this browser: sets the presession and csrf cookies, and returns csrfToken.
curl -s -c jar -b jar http://localhost:3000/api/csrf
# A write without the X-CSRF-Token header: 403 {"error":{"code":"forbidden"}}.
curl -si -b jar -X POST http://localhost:3000/api/register \
-H 'origin: http://localhost:3000' -H 'content-type: application/json' \
-d '{"email":"ada@example.com","password":"<a long passphrase>"}'
# The same write with the token from the first call: 202 {"status":"check-your-email"}.
curl -si -b jar -X POST http://localhost:3000/api/register \
-H 'origin: http://localhost:3000' -H 'content-type: application/json' \
-H 'x-csrf-token: <csrfToken>' \
-d '{"email":"ada@example.com","password":"<a long passphrase>"}'
You observe It shows
403 without the header, 202 with it the signed double-submit token is checked on every write
a [mail] line on the server’s output the mailer you passed to buildAuth is called: a verification mail, or an account-exists mail for a taken address
GET /api/me answers 401 with session_expired a request without a session cookie gets no user

For the whole flow, run the end-to-end test of examples/basic against your Postgres and Redis: DATABASE_URL=... REDIS_URL=... bun run test:integration in that folder. It registers, signs in, verifies the address, reads the account and signs out; answers a wrong password and an unknown address with the same body; refuses cross-site and token-less writes, and a CSRF token minted for another session; binds signed-out tokens to the pre-session id; and checks the trusted-device cookie on sign-in.