Skip to content
James Ross
articlePublished Updated 10 min read

A client sign-off app on Cloudflare D1, Workers and Access

By James Ross

A client sign-off app needs three things: a login the client already has, a record nobody can quietly rewrite, and a way to see when a reviewed page has changed. Cloudflare Access supplies the login, a Cloudflare D1 table of append-only decisions supplies the record, and a content hash on every decision flags stale approvals. Two such apps were built on one Worker pattern; the second one hit an OpenNext runtime crash that a dependency upgrade fixed.

Abstract illustration of a gated ledger on an edge network, representing a Cloudflare D1 sign-off app behind Access.

A content migration ends with a meeting nobody enjoys: the client has to say which pages are approved. Email threads and spreadsheets lose track of which version was approved. This post describes two small review apps built for that moment, both on the edge pattern from moving 15 WordPress sites to Cloudflare Workers: a review site for a retail client’s content sign-off, and a research review desk for fact and measurement cards. Both use Cloudflare D1 for records, Cloudflare Access for identity and a single Worker for the API.

What does a sign-off app have to do?

It has to answer one question reliably: who approved which version of which item, and when. That breaks into four requirements.

Requirement Why it matters How it is met
Real identity An approval from “someone” is worthless Cloudflare Access login, JWT verified in the Worker
Roles Not everyone may approve everything Three roles checked on each write
Tamper-evident history Approvals are evidence Append-only decisions table
Version awareness A page edited after approval is no longer approved Content hash stored with every decision

The app is deliberately small. There is no account system, no password reset and no email flow. The client’s people already have identities that Access can accept, and everything else is a table and a few endpoints.

How is the Worker laid out?

One Worker serves both the API and a static front end. Static files live in an assets directory and are served by the platform; requests under /api/* run the Worker first, using the run_worker_first option, which accepts an array of route patterns (static assets configuration). The pattern keeps the front end cheap and fast and sends only API calls through code.

The configuration is a few lines:

{
  "name": "review-signoff",
  "main": "src/index.ts",
  "assets": {
    "directory": "public",
    "binding": "ASSETS",
    "run_worker_first": ["/api/*"]
  },
  "d1_databases": [
    { "binding": "DB", "database_name": "review-signoff", "database_id": "<id>" }
  ],
  "vars": {
    "ACCESS_MODE": "access",
    "ACCESS_TEAM_DOMAIN": "<team>.cloudflareaccess.com",
    "ACCESS_AUD": "<application audience tag>"
  }
}

The API surface is small: who am I, list decisions, record a decision, record a bulk decision, manage users, export. The first deploy shipped 353 static assets for 347 generated pages, 75 store facts and 150 redirect groups, after one D1 migration (from the deploy log). The pages are generated at build time from the migrated content, so the Worker never renders them; it only records what people decide about them.

How does the Worker verify a Cloudflare Access login?

It reads the Cf-Access-Jwt-Assertion header and verifies the token itself, instead of trusting that Access sat in front. Cloudflare’s guidance is to validate that header against the team’s certs URL, check the issuer matches the team domain, check the audience contains the application’s tag, and check the expiry (Validate JWTs). The Worker does exactly that with the jose library.

import { createRemoteJWKSet, jwtVerify } from "jose";

const jwks = createRemoteJWKSet(
  new URL(`https://${team}/cdn-cgi/access/certs`)
);

const { payload } = await jwtVerify(token, jwks, {
  audience: env.ACCESS_AUD,
  issuer: `https://${team}`,
});
const email = String(payload.email ?? "").trim().toLowerCase();

Four details came out of building it:

  • Fail closed on config. If the team domain or audience is still a placeholder, the Worker answers 500 “Access is not configured”. An unconfigured deploy cannot accidentally accept anything.
  • Cache the key set per team domain. The remote key set is created once and reused across requests in the same isolate.
  • Map every verification failure to 401. A missing token, a bad signature and an expired token all return “Sign-in could not be verified”; a token with no email returns 403.
  • A dev mode that cannot ship. Local development uses ACCESS_MODE=dev, which reads an email from a query parameter, cookie or header. Production sets ACCESS_MODE=access. The two paths are separate code, so dev convenience never widens the production check.

The default workers.dev address is turned off, so the Worker is reachable only through the custom domain, where Access sits. A request to the gated domain and to its API both redirect to the Access login, while the workers.dev URL returns 404 (checked after the first deploy). The edge side of this is the same idea as zero open ports with Cloudflare Tunnel and Access.

The Access applications themselves are self-hosted, each with a 24-hour session and an allowlist of email domains: the agency’s and the client’s. They are hidden from the app launcher, since nobody should find them by browsing.

How do roles work?

A verified email is mapped to a row in a users table, and the row carries a role. The role check runs on every write, so there is no code path where a valid Access login alone can approve something.

The users table holds an email, a name, one of three roles and an active flag. The Worker resolves the user after verifying the JWT, rejects anyone missing or inactive with a 403 and a message that says to ask the agency admin, and checks the role against what each endpoint allows.

Role May do
Reviewer Approve or request changes on items
Owner Approve; approve batch-tier pages, including in bulk
Agency Mark an item fixed, manage users, export approvals

Two rules came from how the review actually runs. A request for changes must carry a non-empty comment, because “changes” with no explanation is not actionable. And bulk approval is an owner-only action capped at 500 batch-tier pages per request, so the people with authority can clear the long tail of low-risk pages in one step while high-tier pages still need individual attention. The caps and role checks live in the Worker, not the front end, because the front end is just a client.

Why is the decisions table append-only?

Because a sign-off is evidence, and a table you can update in place is a table where evidence disappears. Every decision, including a change of mind, is inserted as a new row with who, when, which item and which version.

The schema is short: an identifier, a kind (page, fact or redirect group), the item id, the version, the decision, a comment, the user’s email and a timestamp, with an index on kind, item id and row id so “latest decision for an item” is a single indexed lookup. The decision column has a CHECK constraint listing the allowed values.

That constraint caused the one schema change worth describing. Reviewers wanted to unselect a choice and return an item to open. The answer is a fourth decision value, clear, recorded like any other row. History is kept, the item reads as open, and the export skips cleared items. But SQLite cannot alter a CHECK constraint in place, so the second migration rebuilds the table with the new constraint and copies the existing rows across. D1 migrations are numbered SQL files that run in order and are tracked in a d1_migrations table (D1 migrations), so the rebuild was a normal migration, applied to the remote database during the next deploy. The remote schema was inspected afterward to confirm clear was in the constraint.

An API test covers the behavior: approve, then clear, and assert that two rows exist, the item is absent from the export and an invalid decision value returns 400. The suite was a handful of tests plus a type check at that point, and the test helper was changed to run every .sql file in the migrations folder in sorted order, so tests always run against the real schema history.

How does the app know an approval is stale?

Every decision stores the content version it applied to, a SHA-256 of the page, and the read endpoint compares it to the current version. If they differ, the decision is flagged stale. The export leaves out stale page versions, so a page edited after approval cannot appear approved in the file that downstream tooling reads.

This is the feature clients notice least and need most. Without it, an approval is a statement about a page that may no longer exist. With it, “approved” means “approved as it currently reads”.

Two limits keep it honest. The check compares a hash, so it catches any change but cannot say whether the change matters; trivial edits make an approval stale, which is the safe direction. And a rebuild that produces identical page content leaves the version unchanged, so approvals stay valid.

What happened with OpenNext on the research review desk?

Every HTTP request threw “no such file or directory” while the scheduled trigger kept succeeding, and upgrading the adapter fixed it. The second app is a research review desk built on Next.js and the OpenNext Cloudflare adapter, which transforms a Next.js build to run on Workers (OpenNext for Cloudflare).

The symptoms, from a live wrangler tail: every request, including the favicon, failed with the error, while the minute-by-minute cron trigger completed normally. That split pointed at the request path, not at bindings or the database. The stack trace placed the failure in a process.chdir call inside the adapter’s generated handler, in a function that sets the server’s working directory during initialization. The project was on Next.js 15.5.4 with adapter 1.8.2 and a custom Worker entry file.

The fix was not in the app’s code. Upgrading the adapter from 1.8.2 to 1.20.19, Next.js from 15.5.4 to 15.5.29 and Wrangler from 4.40.0 to 4.169.1 made the build clean and the dev server answer with a redirect on the root path, with no chdir error. One more snag followed: npm ci failed on the build box because its older npm rejected the lockfile as out of sync with the manifest, so the first deploy of the fix still crashed. Running npm install on that machine produced the upgraded tree, and the deploy script was updated to run it for both apps. After the redeploy, wrangler tail showed requests with outcome ok and no exceptions.

The lesson generalizes: a runtime error inside generated adapter code, after the adapter and framework drifted apart, is a version question before it is a code question. Check the adapter’s current release first.

How do you load data into remote D1?

Export locally, then execute the SQL against the remote database with Wrangler. The research desk’s seed was 1,372 cards (1,290 fact, 56 measure, 18 conflict and 8 policy), the same number of card-state rows, 70 research runs and 7 imports. Sample cards and test-user activity were excluded before the export. Wrangler executed 2,891 queries and wrote 11,480 rows (from the import log).

Two habits kept it safe. The export is a plain SQL file, reviewable before it runs. And it ran against the remote database only after the schema was confirmed there, since a seed against a stale schema fails halfway and leaves a partial import.

Which pattern should you use?

Need Fit Why
Small review or approval app, few writers Worker + D1 + Access Cheap, one deploy unit, no servers
Static pages with a few write endpoints Assets plus run_worker_first on /api/* The platform serves files, code runs only for the API
Full Next.js app with server rendering OpenNext adapter on Workers Keeps the framework, adds adapter upkeep
Heavy concurrent writes or complex joins A different database D1 is SQLite semantics

Which should you choose? For a sign-off tool, the small Worker with static assets is the simpler path: less to upgrade and less to crash. Take the OpenNext route when the app genuinely needs server-rendered Next.js, and budget for keeping the adapter current.

What broke and what we changed

The research desk returned errors on every request while cron ran fine. The adapter and framework had drifted apart, and a chdir call in generated code failed. Upgrading the adapter, Next.js and Wrangler fixed it. The check now is to compare adapter versions before reading application code.

npm ci failed on the build box and the old crash persisted. A newer lockfile than the machine’s npm accepted left the fix undeployed. The deploy script now runs npm install for both apps before building.

A decision could not be unselected. The first schema had three decision values and no way to return an item to open. The fix was a clear value written as a new row, which required a table rebuild because SQLite cannot alter a CHECK constraint. History is preserved and the export ignores cleared items.

Approvals could outlive the pages they covered. Pages changed after approval and still looked approved. Each decision now stores the content hash, and stale ones are flagged and left out of the export.

An unconfigured deploy could have accepted traffic. Placeholder Access settings now make the Worker return 500 instead of guessing, and the default workers.dev address is disabled so the Access-gated domain is the only way in.

Frequently asked questions

Can Cloudflare D1 back a small client-facing app?

Yes, for low-volume apps where SQLite semantics are enough. D1 is a hosted database that follows SQLite query rules and is reachable from Workers (D1 overview). A sign-off app has a few tables and a few writers, which fits well. High-write or heavily relational workloads need a different store.

Is Cloudflare Access enough to protect a Worker?

Access is the gate, but the Worker should still verify the JWT. Cloudflare recommends validating the Cf-Access-Jwt-Assertion header, so that a request that reaches the Worker by another path cannot impersonate a user. Disabling the default workers.dev address removes the most obvious other path.

How do you change a CHECK constraint in D1?

SQLite cannot alter a CHECK constraint in place. Write a migration that creates the new table with the updated constraint, copies the rows across, drops the old table and renames the new one. Migrations are numbered SQL files that run in order and are recorded in a d1_migrations table (D1 migrations).

Why make decisions append-only?

Because a sign-off is evidence. If a reviewer can overwrite an approval, nobody can show what was approved when. Appending a new row for every change, including a clear, keeps the full history and lets the export read only the latest effective decision.

What does the OpenNext Cloudflare adapter do?

It takes a Next.js build and transforms it to run on Cloudflare Workers, using the Node.js runtime from Next.js (OpenNext for Cloudflare). It is a moving target, so a runtime error after a Next.js bump is worth checking against a newer adapter before debugging your own code.