Node
For: a developer who wants sign-in in a Node server with a Postgres database.
What it does: you make a Node HTTP server that serves the authtempo routes under /auth. A script signs a person in with a magic link through the real server.
An agent can do these steps with the authtempo MCP server. See Set up an agent.
Before you start
Section titled “Before you start”- Node 22.18 or newer, which runs a
.tsfile with its type stripping. This repo uses Node 26.10.0. - pnpm 12.8.1 and Docker.
- A clone of the authtempo repo. Your app lives in its pnpm workspace, as Choose your stack tells.
The command authtempo init my-app --stack node writes the files of this tutorial for you. authtempo init tells how. The steps below make the same app by hand.
- Copy the folder
examples/nodeof the repo toexamples/my-app. - In
examples/my-app/package.json, changenametomy-app. - Run
pnpm installat the root of the repo. - Start the local Postgres with
docker compose up -dat the root of the repo. - Read
src/app.ts. It builds the auth instance and routes/auth/and/me.
import { createPostgresAdapter, createPostgresLimiter } from "@authtempo/adapter-postgres";import { type Auth, createAuth, type MailPort } from "@authtempo/core";import { readBearer } from "@authtempo/core/credentials";import { createVerifier } from "@authtempo/verify";import type { Sql } from "postgres";
export interface AppOptions { /** The origin where the server answers, such as https://api.example.com. */ baseURL: string; /** At least 32 characters. Keep it in a secret store, never in the code. */ secret: string; sql: Sql; mail: MailPort;}
/** * The header that the server sets from the socket address. The server drops * a copy that the caller sent, so a caller cannot choose its own IP for the * per-IP limits. */export const CLIENT_IP_HEADER = "x-tempo-client-ip";
/** * Your mail transport. Core calls `send` once per mail. Replace the body with * a call to your mail provider. Until then a sign-in request answers 500. */export const mail: MailPort = { async send() { throw new Error("my-app: no mail transport; replace mail.send in src/app.ts"); },};
/** A server of each runtime: Node's http module, or Bun.serve. */export type Serve = ( handler: (request: Request) => Promise<Response>, options: { port: number; hostname: string; origin: string },) => Promise<{ close(): Promise<void> }>;
export function createApp(options: AppOptions): { auth: Auth; fetch(request: Request): Promise<Response>;} { const auth = createAuth({ baseURL: options.baseURL, secret: options.secret, trustedOrigins: [options.baseURL], storage: createPostgresAdapter(options.sql), // The owned limiter counts in Postgres, so every process shares one count. limiter: createPostgresLimiter(options.sql), mail: options.mail, // The default reads cf-connecting-ip, which only Cloudflare sets. Off // Workers any caller can send it, so read the header the server sets. clientIp: (request) => request.headers.get(CLIENT_IP_HEADER), }); // A route that a server which is not the auth app would serve (plan 11d). Here the // auth app is this process, so the verifier reads the key set and the live check // through the handler; another server passes no fetch and reads them over HTTP. const verifier = createVerifier({ issuer: `${options.baseURL}/auth`, audience: options.baseURL, // A sign-out ends access at once: one live check per request. checkSessionEnd: true, fetch: (input, init) => auth.handle(new Request(input, init)), }); return { auth, async fetch(request) { const url = new URL(request.url); if (url.pathname.startsWith("/auth/")) return auth.handle(request); if (url.pathname === "/me") { const s = await auth.session(request); if (!s) return Response.json({ error: "unauthorized" }, { status: 401 }); const res = Response.json({ email: s.user.email }); // A sliding refresh moved the expiry: renew the cookie, or the browser drops it early. const renewed = auth.sessionCookie(request, s); if (renewed) res.headers.append("set-cookie", renewed); return res; } if (url.pathname === "/files") { const r = await verifier.verifyRequest(request); // The auth app limited the live checks: 429. It did not answer: try again later, not "sign in again". if (!r.ok) return Response.json( { error: r.code }, { status: r.code === "rate_limited" ? 429 : 503 }, ); // A refused bearer gets error="invalid_token" (RFC 6750 section 3.1). No bearer, // and a Basic header is none, gets the plain challenge. The verifier reads the // bearer only, never a cookie, so a cookie does not change this answer. if (r.value?.kind !== "session-jwt") return verifier.unauthorized({ invalidToken: readBearer(request) !== null }); return Response.json({ owner: r.value.email }); } return new Response("not found", { status: 404 }); }, };}- Read
src/server-node.ts. It turns each Node request into a fetchRequest, and sets the client IP from the socket.
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import { CLIENT_IP_HEADER, type Serve } from "./app.ts";
/** A fetch Request from a Node request. The body is text: core reads JSON and forms only. */async function toRequest(req: IncomingMessage, origin: string): Promise<Request> { const headers = new Headers(); for (const [name, value] of Object.entries(req.headers)) { if (value === undefined || name === CLIENT_IP_HEADER) continue; for (const v of Array.isArray(value) ? value : [value]) headers.append(name, v); } const ip = req.socket.remoteAddress; if (ip) headers.set(CLIENT_IP_HEADER, ip); const method = req.method ?? "GET"; const chunks: Buffer[] = []; if (method !== "GET" && method !== "HEAD") for await (const chunk of req) chunks.push(chunk as Buffer); const body = chunks.length > 0 ? Buffer.concat(chunks).toString("utf8") : null; return new Request(new URL(req.url ?? "/", origin), { method, headers, body });}
/** Writes a fetch Response to a Node response. Each Set-Cookie stays its own header line. */async function send(res: ServerResponse, answer: Response): Promise<void> { const headers: Record<string, string | string[]> = {}; answer.headers.forEach((value, name) => { if (name !== "set-cookie") headers[name] = value; }); const cookies = answer.headers.getSetCookie(); if (cookies.length > 0) headers["set-cookie"] = cookies; res.writeHead(answer.status, headers); res.end(Buffer.from(await answer.arrayBuffer()));}
export const serveNode: Serve = (handler, options) => { const server = createServer((req, res) => { toRequest(req, options.origin) .then(handler) .then((answer) => send(res, answer)) .catch(() => { res.writeHead(500).end(); }); }); return new Promise((resolve, reject) => { // A port that another process holds fails the listen with EADDRINUSE. // With no listener, that error event ends the process at once. server.once("error", reject); server.listen(options.port, options.hostname, () => { server.off("error", reject); resolve({ close: () => new Promise<void>((done) => server.close(() => done())) }); }); });};- Read
src/main.ts. It reads the settings from the environment, applies the migrations, and starts the server.
// The server of a deploy. Set DATABASE_URL, AUTH_SECRET, BASE_URL, HOST, and// PORT, then run it with Node (`node src/main.ts`) or Bun (`bun src/main.ts`).import { applyPostgresMigrations } from "@authtempo/adapter-postgres";import postgres from "postgres";import { createApp, mail, type Serve } from "./app.ts";
function required(name: string): string { const value = process.env[name]; if (!value) { console.error(`main: set ${name}`); process.exit(2); } return value;}
const baseURL = required("BASE_URL");const sql = postgres(required("DATABASE_URL"), { max: 10 });// Once per process start. The migrations are safe to run from two processes at once.await applyPostgresMigrations(sql);const app = createApp({ baseURL, secret: required("AUTH_SECRET"), sql, mail });const serve: Serve = "Bun" in globalThis ? (await import("./server-bun.ts")).serveBun : (await import("./server-node.ts")).serveNode;await serve(app.fetch, { port: Number(process.env.PORT ?? "3000"), hostname: process.env.HOST ?? "127.0.0.1", origin: baseURL,});console.log(`main: listening for ${baseURL}`);- Run the test. It signs a person in under Node, then under Bun, and prints one line for each runtime.
pnpm turbo run test --filter=my-app// One magic link sign-in through the real HTTP server of this runtime, on the// docker compose Postgres (plan 11a, Review Focus 5). `pnpm test` runs it with// Node and then with Bun. It prints one summary line and exits 1 on a failure.import { applyPostgresMigrations } from "@authtempo/adapter-postgres";import type { MailMessage } from "@authtempo/core";import { DEFAULT_COOKIE_NAME } from "@authtempo/core/credentials";import postgres from "postgres";import { createApp, type Serve } from "../src/app.ts";
const runtime = "Bun" in globalThis ? "bun" : "node";
/** The address of a test server: `node scripts/test-servers.mjs up` writes it, and `pnpm test` passes it. */function serverUrl(name: string): string { const url = process.env[name]; if (url === undefined || url === "") throw new Error( `${name} is not set. Run: node scripts/test-servers.mjs up (pnpm test runs it for you)`, ); return url;}const version = runtime === "bun" ? Bun.version : process.versions.node;const serve: Serve = runtime === "bun" ? (await import("../src/server-bun.ts")).serveBun : (await import("../src/server-node.ts")).serveNode;/** A socket that holds a free port of 127.0.0.1 from the OS, so a listen on the port fails. */async function holdPort(): Promise<{ port: number; close(): Promise<void> }> { const { createServer } = await import("node:net"); const held = createServer(); await new Promise<void>((done, fail) => { held.once("error", fail); held.listen(0, "127.0.0.1", () => done()); }); const address = held.address(); const port = typeof address === "object" && address !== null ? address.port : 0; return { port, close: () => new Promise<void>((done) => held.close(() => done())) };}/** * A free port from the OS. A fixed port met EADDRINUSE when this test and the * init scaffold test of the CLI ran at once (lane item P1 of plan 12g). */async function freePort(): Promise<number> { const probe = await holdPort(); await probe.close(); return probe.port;}/** The most ports that `listen` tries. */const LISTEN_TRIES = 3;/** The error of `listen` when each port that it tried was in use. */class PortInUse extends Error { port: number; constructor(port: number, tries: number) { super(`the listen failed with EADDRINUSE on ${tries} ports`); this.port = port; }}/** * Serves the handler of `make(base)` on a free port. The probe of freePort * closes before the server listens, so another process can take the port. * A listen that fails with EADDRINUSE then tries a new port. */async function listen( make: (base: string) => (request: Request) => Promise<Response>, nextPort: () => Promise<number> = freePort,): Promise<{ base: string; server: { close(): Promise<void> }; tries: number }> { for (let tries = 1; ; tries++) { const port = await nextPort(); const base = `http://127.0.0.1:${port}`; try { const live = await serve(make(base), { port, hostname: "127.0.0.1", origin: base }); return { base, server: live, tries }; } catch (e) { if ((e as { code?: unknown }).code !== "EADDRINUSE") throw e; if (tries >= LISTEN_TRIES) throw new PortInUse(port, tries); } }}/** * The failure line of an error, with a hint at the server that failed. The * listen of the app server runs after the database exists. A port failure is * no fault of Postgres, so its line names the port, not Postgres. */function failureLine(e: unknown): string { const message = e instanceof Error ? e.message : String(e); if (e instanceof PortInUse) return `${message}; another process holds port ${e.port}`; return `${message}; is Postgres up (node scripts/test-servers.mjs up)?`;}const ADMIN_URL = serverUrl("TEMPO_AUTH_PG_URL");const DB = `ex_${runtime}_${crypto.randomUUID().replaceAll("-", "")}`;const DB_URL = ADMIN_URL.replace(/\/[^/]+$/, `/${DB}`);
const failures: string[] = [];let checks = 0;function expectThat(ok: boolean, what: string): void { checks++; if (!ok) failures.push(what);}const json = (body: unknown) => ({ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),});
const admin = postgres(ADMIN_URL, { max: 1, onnotice: () => {} });let sql: ReturnType<typeof postgres> | null = null;let server: { close(): Promise<void> } | null = null;try { // The retry, before the database exists: a held port fails the first // listen, and the next port serves. const held = await holdPort(); try { const ports = [held.port]; const probe = await listen( () => async () => new Response("ok"), async () => ports.shift() ?? freePort(), ); await probe.server.close(); expectThat( probe.tries === 2 && probe.base !== `http://127.0.0.1:${held.port}`, `a listen on a held port took ${probe.tries} tries`, ); } finally { await held.close(); } // Three held ports fail each listen, and the failure line names the last port. const three = [await holdPort(), await holdPort(), await holdPort()]; try { const ports = three.map((h) => h.port); const line = await listen( () => async () => new Response("ok"), async () => ports.shift() ?? freePort(), ).then(async (served) => { await served.server.close(); return `a listen served on try ${served.tries}`; }, failureLine); expectThat( line === `the listen failed with EADDRINUSE on 3 ports; another process holds port ${three[2]?.port}`, `three held ports gave: ${line}`, ); } finally { for (const h of three) await h.close(); }
await admin.unsafe(`CREATE DATABASE ${DB}`); const db = postgres(DB_URL, { max: 2, onnotice: () => {} }); sql = db; await applyPostgresMigrations(db); const sent: MailMessage[] = []; const live = await listen( (base) => createApp({ baseURL: base, secret: "0123456789abcdef0123456789abcdef", sql: db, mail: { async send(m) { sent.push(m); }, }, }).fetch, ); server = live.server; const BASE = live.base;
const ask = await fetch(`${BASE}/auth/magic-link/request`, json({ email: "ada@example.com" })); expectThat(ask.status === 200, `the link request answered ${ask.status}`); const link = /https?:\/\/\S+/.exec(sent.at(-1)?.text ?? "")?.[0]; const token = link ? (new URL(link).searchParams.get("token") ?? "") : ""; expectThat(token.startsWith("ml_"), "no magic link in the mail"); const verify = await fetch(`${BASE}/auth/magic-link/verify`, json({ token })); expectThat(verify.status === 200, `the verify answered ${verify.status}`); const cookie = (verify.headers.getSetCookie()[0] ?? "").split(";")[0] ?? ""; const me = (await (await fetch(`${BASE}/me`, { headers: { cookie } })).json()) as { email?: string; }; expectThat(me.email === "ada@example.com", `/me answered ${JSON.stringify(me)}`); // A server that is not the auth app verifies a session JWT (plan 11d): /files. const minted = (await (await fetch(`${BASE}/auth/token`, { headers: { cookie } })).json()) as { token?: string; }; expectThat(typeof minted.token === "string", "GET /auth/token gave no token"); const files = await fetch(`${BASE}/files`, { headers: { authorization: `Bearer ${minted.token ?? ""}` }, }); // A 404 answers text, not JSON: the check below then names the status. const owner = (await files.json().catch(() => ({}))) as { owner?: string }; expectThat( files.status === 200 && owner.owner === "ada@example.com", `/files answered ${files.status}`, ); const anonymous = await fetch(`${BASE}/files`); expectThat(anonymous.status === 401, `/files with no token answered ${anonymous.status}`); // A Basic header is no bearer: the plain challenge, with no error code (RFC 6750 section 3.1). const basic = await fetch(`${BASE}/files`, { headers: { authorization: "Basic dXNlcjpwYXNz" } }); expectThat( basic.status === 401 && basic.headers.get("www-authenticate") === "Bearer", `/files with a Basic header answered ${basic.status} with ${basic.headers.get("www-authenticate")}`, ); // A refused bearer gets error="invalid_token": the verifier read it and refused it. const refused = await fetch(`${BASE}/files`, { headers: { authorization: "Bearer ts_not_a_token" }, }); expectThat( refused.status === 401 && refused.headers.get("www-authenticate") === 'Bearer error="invalid_token"', `/files with a refused bearer answered ${refused.status} with ${refused.headers.get("www-authenticate")}`, ); // The verifier reads the bearer only: a session cookie beside it does not hide the refusal. const withCookie = await fetch(`${BASE}/files`, { headers: { cookie: `${DEFAULT_COOKIE_NAME}=ts_x`, authorization: "Bearer ts_refused" }, }); expectThat( withCookie.status === 401 && withCookie.headers.get("www-authenticate") === 'Bearer error="invalid_token"', `/files with a cookie and a refused bearer answered ${withCookie.status} with ${withCookie.headers.get("www-authenticate")}`, );} catch (e) { failures.push(failureLine(e));} finally { await server?.close(); await sql?.end({ timeout: 5 }); await admin.unsafe(`DROP DATABASE IF EXISTS ${DB} WITH (FORCE)`).catch(() => {}); await admin.end({ timeout: 5 });}const pass = failures.length === 0 && checks === 12;console.log( `${runtime}-e2e: ${pass ? "PASS" : "FAIL"} version=${version} checks=${checks} failures=${failures.length}`,);for (const f of failures) console.error(`${runtime}-e2e: ${f}`);if (!pass) process.exit(1);- Find the line
node-e2e: PASSin the output. - Replace the body of
mail.sendinsrc/app.tswith a call to your mail provider. - At the root of the repo, start the server with the settings of your deploy.
DATABASE_URL="postgres://USER:PASSWORD@HOST:5432/DATABASE" AUTH_SECRET="<32 characters or more, from openssl rand -base64 32>" BASE_URL="https://api.example.com" HOST=0.0.0.0 PORT=3000 pnpm --filter my-app exec node src/main.tsThe test prints node-e2e: PASS, and the server answers /auth/magic-link/request. After step 11 a person signs in with a mailed link, and /me answers the address.