Workers on D1
For: a developer who wants sign-in in a Cloudflare Worker with a D1 database.
What it does: you make a Worker that serves the authtempo routes under /auth. A test signs a person in with a magic link on a local D1 database.
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, and pnpm 12.8.1.
- The
@authtempopackages are on npm. Add the CLI to your app withpnpm add -D @authtempo/cli, and run each command aspnpm exec authtempo …. The CLI reference lists each command. - A Cloudflare account, for the deploy at the end. A magic link runs on Workers Free. A password needs Workers Paid.
The command authtempo init my-app --stack workers-d1 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-d1of the repo toexamples/my-app. - In
examples/my-app/package.json, changenametomy-app. - Run
pnpm installat the root of the repo. - Read
wrangler.jsonc. It binds the D1 database asDBand turns Node.js compatibility off.
{ "$schema": "node_modules/wrangler/config-schema.json", "name": "my-app", "main": "src/index.ts", "compatibility_date": "2026-09-30", // From compatibility date 2026-08-04 Workers turn nodejs_compat on by // default. Core and the D1 adapter use no Node.js API, so these two flags // turn it off. The test bundles the Worker and fails on any node: import. "compatibility_flags": ["no_nodejs_compat", "no_nodejs_compat_v2"], "vars": { // The origin of this Worker. Change it to your own origin before a deploy. "BASE_URL": "https://example.test" }, "d1_databases": [ { "binding": "DB", "database_name": "my-app", // Replace this with the id that `wrangler d1 create my-app` prints. // The test runs on a local database and needs no real id. "database_id": "00000000-0000-0000-0000-000000000000", // The adapter package ships the migrations. wrangler reads this path // relative to this file. "migrations_dir": "node_modules/@authtempo/adapter-d1/migrations" } ], // 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 D1 forever. "triggers": { "crons": ["17 * * * *"] } // AUTH_SECRET is a secret: `wrangler secret put AUTH_SECRET`. The test sets // it in vitest.config.ts.}- Read
src/index.ts. It mountsauth.handleunder/auth, serves/me, and runs the sweep on a cron trigger.
import { createD1Adapter, createD1Limiter } from "@authtempo/adapter-d1";import { type Auth, type AuthConfig, createAuth, type HooksConfig, type MailPort,} from "@authtempo/core";import { workersLogsSink } from "@authtempo/observe/workers-logs";
/** The bindings and vars of wrangler.jsonc, and the secret of `wrangler secret put AUTH_SECRET`. */export interface Env { DB: D1Database; BASE_URL: string; AUTH_SECRET: string;}
/** * Your mail transport. Core calls `send` once per mail: a magic link, an * email code, a reset link. Replace the body with a call to your mail * provider. Until then a sign-in request answers 500, so a deploy with no * mail fails at once and not in silence. */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 measure entry * (src/measure.ts) adds the password config and its own sink with it. */export function createWorker( mailPort: MailPort, hooks?: HooksConfig, more?: (env: Env) => Partial<AuthConfig>,) { // One auth instance per isolate. The bindings stay the same for the life of the isolate. let auth: Auth | null = null; const getAuth = (env: Env): Auth => (auth ??= createAuth({ baseURL: env.BASE_URL, secret: env.AUTH_SECRET, trustedOrigins: [env.BASE_URL], storage: createD1Adapter(env.DB), // The owned limiter counts in D1, so every isolate shares one count. // The default limiter counts per isolate, and is for tests only. limiter: createD1Limiter(env.DB), 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) : {}), }));
return { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { const url = new URL(request.url); const a = getAuth(env); const viaHandle = url.pathname.startsWith("/auth/"); try { // The events flush after the answer. Bound on purpose: an unbound // ctx.waitUntil throws Illegal invocation (Cloudflare Workers best // practices, read 2026-10-14). if (viaHandle) return await a.handle(request, { waitUntil: (p) => ctx.waitUntil(p) }); if (url.pathname === "/me") { const s = await a.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 = a.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. A call outside it, such as the session // read of /me, flushes here, or its events wait for the next handle call. if (!viaHandle) ctx.waitUntil(a.observe.flush()); } }, // 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> { ctx.waitUntil(getAuth(env).api.sweepExpired()); }, } satisfies ExportedHandler<Env>;}
export default createWorker(mail);- Run the test. It applies the migrations to a local D1 database and signs a person in.
pnpm turbo run test --filter=my-appimport { createExecutionContext, env } from "cloudflare:test";import type { MailMessage } from "@authtempo/core";import { expect, it } from "vitest";import worker, { createWorker } from "../src/index";
const BASE = "https://example.test";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 D1 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, createExecutionContext(), ); 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, createExecutionContext(), ); expect(verify.status).toBe(200); const cookie = (verify.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; expect(cookie.startsWith("__Host-tempo_session=ts_")).toBe(true);
const me = await app.fetch( new Request(`${BASE}/me`, { headers: { cookie } }), env, createExecutionContext(), ); 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, createExecutionContext(), ); expect(res.status).toBe(500);});- Create the real database with
pnpm --filter my-app exec wrangler d1 create my-app. - Copy the
database_idthat the command prints intowrangler.jsonc. - Apply the migrations to the real database.
pnpm --filter my-app exec wrangler d1 migrations apply my-app --remote- 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.
The test passes, and the Worker answers /auth/magic-link/request. After step 13 a person signs in with a mailed link, and /me answers the address.