Workers on Postgres through Hyperdrive
For: a developer who wants sign-in in a Cloudflare Worker with a Postgres database.
What it does: you make a Worker that reaches Postgres through Hyperdrive and serves the authtempo routes under /auth. A test signs a person in with a magic link on a local Postgres.
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, pnpm 12.8.1, and Docker.
- A clone of the authtempo repo. Your app lives in its pnpm workspace, as Choose your stack tells.
- A Postgres database for the deploy. Postgres tells how to migrate it.
- A Cloudflare account, on Workers Paid if you add passwords.
The command authtempo init my-app --stack workers-postgres 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/worker-postgresof 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 -d postgresat the root of the repo. ThelocalConnectionStringofwrangler.jsoncnames its address. - Read
wrangler.jsonc. It keepsnodejs_compaton, because the driver opens a socket through Node.js APIs.
{ "$schema": "node_modules/wrangler/config-schema.json", "name": "my-app", "main": "src/index.ts", "compatibility_date": "2026-09-30", // postgres.js opens a TCP socket through Node.js APIs, so this Worker needs // nodejs_compat. It is on by default from the 2026-08-04 compatibility date. // It stays explicit so that a copy of the D1 config's no_nodejs_compat does // not break the driver. Core itself uses none (spec 4). "compatibility_flags": ["nodejs_compat"], "vars": { // The origin of this Worker. Change it to your own origin before a deploy. "BASE_URL": "https://example.test" }, "hyperdrive": [ { "binding": "HYPERDRIVE", // Replace this with the id that `wrangler hyperdrive create` prints. "id": "00000000000000000000000000000000", // `wrangler dev` connects here instead: the Postgres of the repo's docker compose. "localConnectionString": "postgres://tempo:tempo@localhost:5439/tempo_auth" } ], // Workers Logs keeps the events of the Workers Logs sink of // @authtempo/observe (plan 12h). A default is not a promise, so this block // states it. Read 2026-10-14 at developers.cloudflare.com/workers/ // observability/logs/workers-logs/: Free 200,000 log events a day and 3 days // of retention; Paid 20 million a month, then $0.60 a million, and 7 days; // from 2026-12-01 Workers Logs moves to Cloudflare Observability pricing. "observability": { "enabled": true, // 1 keeps every request. A rate below 1 drops whole requests, and with // them the sign-in events of those requests (OWASP ASVS 5.0.0 16.3.1). // Lower it only with the OTLP sink as the record of security events. "head_sampling_rate": 1 }, // The sweep deletes expired links, codes, and sessions. Without a trigger // they stay in Postgres forever. "triggers": { "crons": ["17 * * * *"] } // AUTH_SECRET is a secret: `wrangler secret put AUTH_SECRET`.}- Read
src/index.ts. It opens one client for each request and ends it after the answer.
import { createPostgresAdapter, createPostgresLimiter } from "@authtempo/adapter-postgres";import { type AuthConfig, createAuth, type HooksConfig, type MailPort } from "@authtempo/core";import { workersLogsSink } from "@authtempo/observe/workers-logs";import postgres from "postgres";
/** The bindings and vars of wrangler.jsonc, and the secret of `wrangler secret put AUTH_SECRET`. */export interface Env { HYPERDRIVE: Hyperdrive; BASE_URL: string; AUTH_SECRET: string;}
/** * 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/index.ts"); },};
/** * The Worker. The test passes a mail port that keeps the mails, and hooks of its own. * `more` adds config keys for one env, after the keys below. The test adds `phone` with it. */export function createWorker( mailPort: MailPort, hooks?: HooksConfig, more?: (env: Env) => Partial<AuthConfig>,) { return { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { // One client per request, as the adapter README asks on Workers: one // connection, no prepared statements, and no type fetch through Hyperdrive. // Warning: with max 1, a before hook must not query this client. See the // one-connection rule in the docs. const sql = postgres(env.HYPERDRIVE.connectionString, { max: 1, prepare: false, fetch_types: false, }); // createAuth sends no query, so the client needs no end when it throws. const auth = createAuth({ baseURL: env.BASE_URL, secret: env.AUTH_SECRET, trustedOrigins: [env.BASE_URL], storage: createPostgresAdapter(sql), // The owned limiter counts in Postgres, so every isolate shares one count. limiter: createPostgresLimiter(sql), mail: mailPort, ...(hooks ? { hooks } : {}), // Each event of core goes to Workers Logs as one JSON object. wrangler.jsonc // turns the logs on. With a sink, core writes no console line of its own. // The sink scrubs the secret of the config from each field, as the last guard. observe: { sink: workersLogsSink({ secrets: [env.AUTH_SECRET] }) }, ...(more ? more(env) : {}), }); // Some routes do work after the answer, such as the phone code SMS. That // work goes to waitUntil and still queries this client. So the client // ends only after each promise kept here settles. The call keeps // ctx.waitUntil bound: an unbound ctx.waitUntil throws Illegal invocation // (Cloudflare Workers best practices, read 2026-10-14). const kept: Promise<unknown>[] = []; const waitUntil = (p: Promise<unknown>) => { kept.push(p); ctx.waitUntil(p); }; const url = new URL(request.url); const viaHandle = url.pathname.startsWith("/auth/"); try { // The events flush after the answer. if (viaHandle) return await auth.handle(request, { waitUntil }); 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; } return new Response("not found", { status: 404 }); } finally { // handle flushes its own events. This Auth lives for one request, so an // event of a call outside handle, such as the session read of /me, // flushes here or never. The flush uses no connection. if (!viaHandle) ctx.waitUntil(auth.observe.flush()); // An end at once refuses each query of the work after the answer. The // answer is still 200, but no SMS, no mail, and no row go out. ctx.waitUntil(Promise.allSettled(kept).then(() => sql.end({ timeout: 5 }))); } }, // The cron trigger of wrangler.jsonc runs this. It deletes the rows that no flow can use. async scheduled( _controller: ScheduledController, env: Env, ctx: ExecutionContext, ): Promise<void> { const sql = postgres(env.HYPERDRIVE.connectionString, { max: 1, prepare: false, fetch_types: false, }); const auth = createAuth({ baseURL: env.BASE_URL, secret: env.AUTH_SECRET, trustedOrigins: [env.BASE_URL], storage: createPostgresAdapter(sql), limiter: createPostgresLimiter(sql), mail: mailPort, // The sweep flushes its own events before it answers. observe: { sink: workersLogsSink({ secrets: [env.AUTH_SECRET] }) }, }); ctx.waitUntil(auth.api.sweepExpired().finally(() => sql.end({ timeout: 5 }))); }, } satisfies ExportedHandler<Env>;}
export default createWorker(mail);- Read
scripts/migrate.ts. It applies the migrations. Run it on each deploy, before the new Worker serves a request.
// Applies the migrations of @authtempo/adapter-postgres. Run it on each// deploy, before the new Worker serves a request:// DATABASE_URL="postgres://…" node scripts/migrate.ts// It is safe to run twice, also from two machines at once (adapter README).import { applyPostgresMigrations } from "@authtempo/adapter-postgres";import postgres from "postgres";
const url = process.env.DATABASE_URL;if (!url) { console.error("migrate: set DATABASE_URL to the connection string of your database"); process.exit(2);}const sql = postgres(url, { max: 1 });try { await applyPostgresMigrations(sql); console.log("migrate: done");} finally { await sql.end({ timeout: 5 });}- Run the test. It makes a new database, applies the migrations, and signs a person in.
pnpm turbo run test --filter=my-appimport { applyPostgresMigrations } from "@authtempo/adapter-postgres";import { createPbkdf2PasswordHash, type MailMessage } from "@authtempo/core";import { createRecordingSms } from "@authtempo/core/testing";import postgres from "postgres";import { afterAll, beforeAll, expect, it } from "vitest";import worker, { createWorker, type Env } from "../src/index";
// The tsconfig has workers-types only, so type the one Node global this file reads.const processEnv = ( globalThis as unknown as { process: { env: Record<string, string | undefined> } }).process.env;
/** 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 = processEnv[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 ADMIN_URL = serverUrl("TEMPO_AUTH_PG_URL");const DB = `ex_${crypto.randomUUID().replaceAll("-", "")}`;const DB_URL = ADMIN_URL.replace(/\/[^/]+$/, `/${DB}`);const BASE = "https://example.test";
const env: Env = { HYPERDRIVE: { connectionString: DB_URL } as unknown as Hyperdrive, BASE_URL: BASE, AUTH_SECRET: "0123456789abcdef0123456789abcdef",};const pending: Promise<unknown>[] = [];const ctx = { waitUntil(p: Promise<unknown>) { pending.push(p); }, passThroughOnException() {},} as unknown as ExecutionContext;
beforeAll(async () => { const admin = postgres(ADMIN_URL, { max: 1, onnotice: () => {} }); try { await admin.unsafe(`CREATE DATABASE ${DB}`); } catch (e) { // A refused connection arrives as an AggregateError with an empty message, // so name the error code when there is one. const why = (e as { code?: string }).code ?? (e as Error).message; throw new Error( `this test needs Postgres at ${ADMIN_URL}: ${why}. Run: node scripts/test-servers.mjs up`, ); } finally { await admin.end({ timeout: 5 }); } const sql = postgres(DB_URL, { max: 1, onnotice: () => {} }); await applyPostgresMigrations(sql); await sql.end({ timeout: 5 });});
// The drop is slow while other suites create, write, and drop databases on// the same Postgres. Measured on 2026-10-20, it took 0.03 to 0.8 s alone.// While core, compat, and the adapters ran their tests, it took 8.3, 15.4,// and 28.6 s (one-minute load 13 to 28). The default hook limit of 10 s// failed the unfiltered runs, so the drop gets 60 s, about twice the worst.afterAll(async () => { await Promise.all(pending); const admin = postgres(ADMIN_URL, { max: 1, onnotice: () => {} }); await admin.unsafe(`DROP DATABASE IF EXISTS ${DB} WITH (FORCE)`); await admin.end({ timeout: 5 });}, 60_000);
const json = (path: string, body: unknown) => new Request(`${BASE}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), });
it("signs a person in by magic link on Postgres and reads /me with the session cookie", async () => { const sent: MailMessage[] = []; const app = createWorker({ async send(m) { sent.push(m); }, }); const ask = await app.fetch( json("/auth/magic-link/request", { email: "ada@example.com" }), env, ctx, ); expect(await ask.json()).toEqual({ sent: true }); const link = /https:\/\/\S+/.exec(sent.at(-1)?.text ?? "")?.[0] ?? ""; const token = new URL(link).searchParams.get("token") ?? "";
const verify = await app.fetch(json("/auth/magic-link/verify", { token }), env, ctx); expect(verify.status).toBe(200); const cookie = (verify.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
const me = await app.fetch(new Request(`${BASE}/me`, { headers: { cookie } }), env, ctx); expect(await me.json()).toEqual({ email: "ada@example.com" });});
it("answers 500 to a sign-in request until the app has a mail transport", async () => { const res = await worker.fetch( json("/auth/magic-link/request", { email: "ada@example.com" }), env, ctx, ); expect(res.status).toBe(500);});
// The phone code request and the code-mode sign-up do their store work and// their send after the answer (ruling 23 of plan 12i). That work queries the// per-request client, so the Worker must end the client after it, not at once.it("sends the phone code and the sign-up code after the answer on the per-request client", async () => { const sms = createRecordingSms(); const sent: MailMessage[] = []; const app = createWorker( { async send(m) { sent.push(m); }, }, undefined, () => ({ password: { hash: createPbkdf2PasswordHash({ iterations: 1000 }), verifyBy: "code" }, phone: { sms, regions: ["+1"], signUp: true }, }), );
const phone = await app.fetch(json("/auth/phone/request", { phone: "+14155550100" }), env, ctx); expect(phone.status).toBe(200); const signUp = await app.fetch( json("/auth/password/sign-up", { email: "grace@example.com", password: "correct horse battery", }), env, ctx, ); expect(signUp.status).toBe(200); await Promise.all(pending);
expect(sms.sent).toHaveLength(1); expect(sent.map((m) => m.to)).toEqual(["grace@example.com"]); const sql = postgres(DB_URL, { max: 1, onnotice: () => {} }); try { const users = await sql< { n: number }[] >`SELECT count(*)::int AS n FROM ta_user WHERE email = 'grace@example.com'`; expect(users[0]?.n).toBe(1); const codes = await sql< { purpose: string }[] >`SELECT purpose FROM ta_verification WHERE purpose IN ('phone-otp', 'password-verify-otp') ORDER BY purpose`; expect(codes.map((c) => c.purpose)).toEqual(["password-verify-otp", "phone-otp"]); } finally { await sql.end({ timeout: 5 }); }});- Make a Hyperdrive config for your database.
pnpm --filter my-app exec wrangler hyperdrive create my-app --connection-string="postgres://USER:PASSWORD@HOST:5432/DATABASE"- Copy the
idthat the command prints intowrangler.jsonc. - Apply the migrations to your database.
DATABASE_URL="postgres://USER:PASSWORD@HOST:5432/DATABASE" pnpm --filter my-app migrate- Replace the body of
mail.sendinsrc/index.tswith a call to your mail provider. - Set
BASE_URLinwrangler.jsoncto the origin of your Worker. - Make a secret of 32 characters or more and an estimate of 100 bits or more with
openssl rand -base64 32. Store it withpnpm --filter my-app exec wrangler secret put AUTH_SECRET. - Deploy the Worker with
pnpm --filter my-app exec wrangler deploy.
Two test files run the code of the Worker on Node against the local Postgres. The file test/workerd.test.ts runs the Worker in workerd, and the local form of the Hyperdrive binding connects it to that Postgres. No test runs the Hyperdrive service, so do one real sign-in after the first deploy.