valfz

Workers from first principles

Relational data with D1

Add a D1 database with a migration, record visits with prepared statements, and use ctx.waitUntil so the write never delays the redirect.

lesson
06 of 08
read
12 min

Counting visits means a write on every redirect and a number that many requests update at once. Lesson 5 showed why KV cannot hold that number. D1 is a SQLite database that a Worker reaches through a binding. One inserted row per visit cannot lose an update, and SQL does the counting. This lesson adds the database, creates its schema with a migration, records visits with prepared statements, and uses ctx.waitUntil() so that the write never delays the redirect.

Add the database binding

A D1 binding takes a name and an id. Under cf dev, a binding with only a name gets a local database, and the local simulation calls it DB-shortlinks after the binding and the Worker. The migration commands used below do not accept that:

pnpm exec cf d1 migrations list DB-shortlinks --local
┌ Error
│ Expected a D1 database ID, but received <database>="DB-shortlinks". Database
│ names and binding names are not accepted.
└

They want the database’s UUID. The real database is created in lesson 8, and until then any UUID will do locally. Generate one:

node -e "console.log(crypto.randomUUID())"

Then declare the binding with it. The examples use the ID below, so substitute your own in every command.

cloudflare.config.ts
@@ -13,6 +13,7 @@
 			LIMITS: bindings.json({ codeLength: 6, maxUrlLength: 2048 }),
 			ADMIN_TOKEN: bindings.secret(),
 			LINKS: bindings.kv(),
+			DB: bindings.d1({ name: "shortlinks", id: "8f0c4c3e-52a1-4b7d-9a35-1c2f6d7e8a90" }),
 		},
 	},
 }));

Local data is stored under this ID. When lesson 8 replaces it with the real one, the local database starts empty again and you re-apply the migration.

Write the schema as a migration

A migration is a numbered SQL file. Create an empty one:

pnpm exec cf d1 migrations create create_visits

The first time, the command offers to create the migrations directory. It then writes migrations/0001_create_visits.sql containing a header comment. Add the schema below it:

migrations/0001_create_visits.sql
-- Migration number: 0001 	 2026-11-28T21:43:18.995Z
CREATE TABLE visits (
	id INTEGER PRIMARY KEY,
	code TEXT NOT NULL,
	visited_at TEXT NOT NULL,
	referrer TEXT,
	country TEXT
);

CREATE INDEX visits_code_visited_at ON visits (code, visited_at);

SQLite has no timestamp type. ISO 8601 strings in a TEXT column sort correctly as text, and new Date().toISOString() produces them. The index covers the query this lesson runs: all visits for one code, with the latest timestamp.

list shows the migrations that have not been applied yet, and apply runs them:

pnpm exec cf d1 migrations list 8f0c4c3e-52a1-4b7d-9a35-1c2f6d7e8a90 --local
[
  {
    "Name": "0001_create_visits.sql"
  }
]
pnpm exec cf d1 migrations apply 8f0c4c3e-52a1-4b7d-9a35-1c2f6d7e8a90 --local
pnpm exec cf d1 migrations list 8f0c4c3e-52a1-4b7d-9a35-1c2f6d7e8a90 --local

apply asks for confirmation in a terminal and reports the status of each file. Afterwards the list is empty:

[]

Applied migrations are recorded in a table named d1_migrations inside the database, so running apply again does nothing. As with KV, the --local flag is what keeps these commands on your machine. Without it, cf d1 migrations apply runs against the remote database.

Prepared statements

src/visits.ts
export type Visit = {
	code: string;
	referrer: string | null;
	country: string | null;
};

export type VisitStats = {
	visits: number;
	lastVisitedAt: string | null;
};

export async function recordVisit(db: D1Database, visit: Visit): Promise<void> {
	await db
		.prepare("INSERT INTO visits (code, visited_at, referrer, country) VALUES (?1, ?2, ?3, ?4)")
		.bind(visit.code, new Date().toISOString(), visit.referrer, visit.country)
		.run();
}

export async function visitStats(db: D1Database, code: string): Promise<VisitStats> {
	const row = await db
		.prepare(
			"SELECT COUNT(*) AS visits, MAX(visited_at) AS lastVisitedAt FROM visits WHERE code = ?1",
		)
		.bind(code)
		.first<VisitStats>();
	return row ?? { visits: 0, lastVisitedAt: null };
}

prepare() takes SQL with numbered placeholders, bind() supplies the values, and a final call executes the statement. run() is for statements whose rows you do not need, first() resolves to the first row or null, and all() returns every row. The prepared statements reference lists the rest.

Values passed through bind() are never spliced into the SQL text. The referrer is a header an attacker controls, and binding is what makes a hostile value such as '); DROP TABLE visits; -- end up as a string in a column.

The column aliases in the SELECT match the property names of VisitStats, so the row can be returned as is.

Record the visit after the response

src/index.ts
@@ -1,9 +1,12 @@
 import { requireToken } from "./auth.ts";
 import { HttpError, readJsonObject } from "./http.ts";
 import { createLink, getLink } from "./links.ts";
+import { recordVisit, visitStats } from "./visits.ts";
 
+type WorkerRequest = Request<unknown, IncomingRequestCfProperties>;
+
 type RouteArgs = {
-	request: Request;
+	request: WorkerRequest;
 	env: Env;
 	ctx: ExecutionContext;
 	params: Record<string, string | undefined>;
@@ -31,7 +34,7 @@
 	},
 } satisfies ExportedHandler<Env>;
 
-async function route(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
+async function route(request: WorkerRequest, env: Env, ctx: ExecutionContext): Promise<Response> {
 	const allowed: string[] = [];
 	for (const [method, pattern, handler] of routes) {
 		const match = pattern.exec(request.url);
@@ -63,14 +66,25 @@
 
 async function showLink({ env, params }: RouteArgs): Promise<Response> {
 	const code = params.code ?? "";
-	const link = await getLink(env.LINKS, code);
+	const [link, stats] = await Promise.all([getLink(env.LINKS, code), visitStats(env.DB, code)]);
 	if (!link) throw new HttpError(404, "no such link");
-	return Response.json({ code, ...link });
+	return Response.json({ code, ...link, ...stats });
 }
 
-async function followLink({ env, params }: RouteArgs): Promise<Response> {
-	const link = await getLink(env.LINKS, params.code ?? "");
+async function followLink({ request, env, ctx, params }: RouteArgs): Promise<Response> {
+	const code = params.code ?? "";
+	const link = await getLink(env.LINKS, code);
 	if (!link) throw new HttpError(404, "no such link");
+
+	const visit = {
+		code,
+		referrer: request.headers.get("Referer"),
+		country: request.cf?.country ?? null,
+	};
+	ctx.waitUntil(
+		recordVisit(env.DB, visit).catch((err) => console.error("recordVisit failed:", err)),
+	);
+
 	return Response.redirect(link.url, 302);
 }
 

request.cf is metadata Cloudflare attaches to an incoming request, including the visitor’s country. Its type is only known on the request type the runtime passes to handlers, hence the WorkerRequest alias. In local development the dev server fills request.cf with values for your own connection.

The important line is ctx.waitUntil(...). The visitor is waiting for a redirect and has no use for the result of the insert, so the handler returns the response at once and registers the write as work to finish afterwards. The runtime keeps the invocation alive until that promise settles, for at most 30 seconds after the response.

Registering the promise is not optional. To see why, the write was delayed by 200 ms and started as a bare promise:

void scheduler.wait(200).then(() => recordVisit(env.DB, visit)).then(() => console.log("recorded"));

Three redirects produced no rows and no log line. When the response was sent the invocation ended, and the pending work was dropped. With the same promise passed to ctx.waitUntil(), three redirects each returned in about 9 ms (curl’s time_total against the local dev server). recorded was logged three times, and the rows were there.

The .catch() is the other half. A promise that rejects inside waitUntil cannot change a response that has already been sent, so nobody would hear about the failure. On a database where the migration had not been applied, the redirect still returned 302 and the log showed why no visit was stored:

recordVisit failed: Error: D1_ERROR: no such table: visits: SQLITE_ERROR

That is the trade this design makes. A visit can be lost when the write fails, and in exchange the redirect is never slowed or broken by analytics. Where losing the work is not acceptable, the context documentation points to Queues, which retry.

Read the numbers back

showLink now reads from both stores at once. The two lookups do not depend on each other, so Promise.all lets them overlap. Create a link, follow it three times (once with a Referer header), and ask for its record:

curl -i -H 'Referer: https://news.example.com/item/1' http://localhost:8791/v6cjeb
curl http://localhost:8791/api/links/v6cjeb
HTTP/1.1 302 Found
...
location: https://developers.cloudflare.com/d1/
...

{"code":"v6cjeb","url":"https://developers.cloudflare.com/d1/","createdAt":"2026-11-28T22:11:53.310Z","visits":3,"lastVisitedAt":"2026-11-28T22:11:55.517Z"}

cf d1 raw runs SQL against the local database:

pnpm exec cf d1 raw 8f0c4c3e-52a1-4b7d-9a35-1c2f6d7e8a90 --sql 'SELECT id, code, visited_at, referrer FROM visits ORDER BY id' --local
[
  {
    "success": true,
    "results": {
      "columns": [
        "id",
        "code",
        "visited_at",
        "referrer"
      ],
      "rows": [
        [
          1,
          "v6cjeb",
          "2026-11-28T22:11:55.483Z",
          null
        ],
        [
          2,
          "v6cjeb",
          "2026-11-28T22:11:55.500Z",
          "https://news.example.com/item/1"
        ],
        [
          3,
          "v6cjeb",
          "2026-11-28T22:11:55.517Z",
          null
        ]
      ]
    },
...

The project now uses each store for what it is good at. KV answers the read on the hot path, where a cached copy near the visitor is what you want. D1 takes the writes, where every row has to count.

pnpm test still passes even though the test environment’s database has no tables, because the code the test requests is not in KV and the handler returns before it touches D1. Lesson 8 tests the visit path properly. Lesson 7 adds the front end.

Exercises

  1. Add GET /api/links/:code/visits returning the most recent visits, newest first, with an optional limit query parameter (default 20, maximum 100) passed to SQL through bind(). The result is correct when the array is ordered by visited_at descending, ?limit=1 returns one element, and ?limit=abc returns 400.
  2. Add GET /api/links/:code/daily returning visits per day, for example [{"day":"2026-11-28","visits":3}]. Do the grouping in SQL. substr(visited_at, 1, 10) extracts the day from an ISO timestamp.
  3. Create a second migration, add_user_agent, that adds a nullable user_agent column, and record the User-Agent header with each visit. The result is correct when migrations list shows the new file before apply and [] after, new rows carry a user agent, and old rows hold NULL.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are