A Static Site Can Use Workers Without a Custom Handler
A three-person documentation team publishes a generated site: one HTML file per article, a stylesheet, a JavaScript bundle, and a 404.html. Nothing in that site needs a database at request time. On their previous host, a small server read files off disk and did nothing else.
On Workers, that server disappears. A static asset is a file uploaded with your deployment and served from Cloudflare's network — HTML, CSS, JavaScript, images, fonts, JSON. The assets directory is the local folder Wrangler uploads, usually a build output such as dist/. A deployment — Cloudflare also calls the uploaded artifact a version — is that folder plus, optionally, a Worker script, uploaded as one unit. There is no origin to keep patched or awake.
Think of a reading room with a shelf and a librarian. Every request checks the shelf first. If the exact file is there, it is handed over and the librarian is never paged. Only when the shelf has no match does your code get involved. That ordering is the entire design, and nearly every routing surprise in this article follows from it.
The smallest deployment needs no handler at all. Declare the assets directory, point it at the build output, and deploy.
There is no request code. No main key and no exported handler: Cloudflare serves matching files, returns 404 Not Found for everything else, and attaches validation and cache headers for you.
A script can arrive later without reshaping the deployment. main appears, the same directory is still served the same way, and only unmatched requests start reaching your code.
Three more terms make the rest of the article readable. A Worker script is the module that exports a fetch handler. An assets binding — conventionally env.ASSETS — is a handle on the uploaded collection that code can call to ask the shelf a question directly. The edge cache is the per-location copy that makes the second request cheaper than the first.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
R[GET /pages/series/cloudflare/guide.html] --> M{File exists in assets.directory?}
M -->|yes| S[Serve file from edge cache
no Worker invocation]
M -->|no| H{main defined?}
H -->|no| N[404 Not Found]
H -->|yes| W[Worker fetch handler runs]
W -->|defers| A[env.ASSETS.fetch request]
A --> F{not_found_handling}
F -->|none| N2[404 Not Found]
F -->|404-page| P[nearest 404.html
status 404]
F -->|single-page-application| I[index.html
status 200]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class R primary;
class M,H,W,A,F,P,I secondary;
class S ok;
class N,N2 danger;
Figure 1 follows one request through that order. The first branch is the important one: a matching file is served without invoking anything, so a correct deployment of a static site has no per-request compute cost at all. The lower branches only exist when you add a script, and the fallback choice at the bottom is a configuration decision rather than something the platform infers.
Figure 2 redraws the same flow as layers and boundaries. The dashed container is a trust and network boundary, not a hop: the browser talks to the edge, the edge consults the uploaded collection, and the optional script is inside the same deployment. There is no arrow leaving Cloudflare, because in this architecture there is nowhere for it to go.
A matching file wins
A file that matches the request prevents your code from running. That is what makes an assets-only site free to serve, and it is also what causes the first production incident most teams hit. Adding an /api/health route does not protect the path: a stray file at dist/api/health — a placeholder, a fixture, a generated debug file — wins, and your handler never runs.
Assets, APIs, and Worker-First Routing
Six weeks later the same team adds two things: a JSON endpoint for search, and a server-rendered dashboard for internal metrics. They now have four request shapes on one hostname, and each shape needs a different answer to "who decides?"
The distinction that matters is not static versus dynamic. It is whether a file can answer the request, and if not, what should happen instead. Workers exposes that as two independent settings: an asset-precedence switch and a fallback policy.
| Requirement | Request shape | Configuration that decides it | Characteristic failure |
|---|---|---|---|
| Static page or file | GET /pages/series/cloudflare/guide.html, file exists in dist/ | assets.directory, plus html_handling for trailing-slash and .html forms | Build did not emit the file, so a valid-looking URL returns the fallback instead |
| Client-side SPA route | GET /settings with Sec-Fetch-Mode: navigate, no file behind it | not_found_handling: "single-page-application" | Every typo returns 200 with index.html, so broken links look healthy to crawlers |
| Server-rendered page | GET /dashboard, HTML built per request | main plus run_worker_first, or no matching asset at all | _headers rules do not apply to the Worker's response; a missing fallback hides deep-link bugs |
| JSON API | GET /api/search?q=edge | main plus run_worker_first: ["/api/*"] | A file at the same path shadows the Worker; a browser navigation may receive HTML instead of JSON |
Precedence, not reachability
run_worker_first is widely misread as "turn on my API." Unmatched requests already reach the Worker by default, so a plain endpoint works without it. The setting changes precedence, not reachability: it makes the script run before the shelf is consulted. You need it when a path could plausibly match both a file and code, or when an authorization check, request logging, an A/B assignment, or bootstrap data must happen before any asset is served.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
participant B as Browser
participant E as Edge router
participant W as Worker script
participant A as Asset collection
B->>E: GET /api/search?q=edge
E->>W: run_worker_first matches /api/*
W-->>B: 200 application/json
B->>E: GET /pages/series/cloudflare/guide.html
E->>A: exact path match
A-->>B: 200 text/html, ETag, revalidate
B->>E: GET /api/unknown
E->>W: matches /api/*
W-->>B: 404 application/json
B->>E: GET /settings in SPA mode
E->>A: no file at this path
A-->>B: 200 index.html from SPA fallback
Note over E,W: Free-plan request cap exceeded
with run_worker_first returns 429
instead of falling back to an asset
Note over E,A: No match and no script means a plain 404
Figure 3 puts the four shapes in one exchange and adds the two branches that produce confusing tickets: a matched API path that the free-tier cap rejects outright, and a path with neither a file nor a script.
A cap is not a fallback
When run_worker_first patterns match and you exceed the free request allowance, Cloudflare returns 429 Too Many Requests; it does not quietly serve the asset instead. Negative patterns — entries prefixed with an exclamation mark — keep going to assets and keep working.
The example below is the configuration this article keeps referring to. The Worker only owns /api/*; everything else is left to the asset collection.
The TypeScript panel is deliberately small: two API paths and a deferral. The JSON panel is the part that decides behavior: binding is only valid because main exists, so a Worker with assets and no script must omit it.
Exceptions are written with a leading !, and negative patterns win over positive ones regardless of order.
The billing boundary is simple. Asset requests are free and unlimited, storage for assets carries no separate charge, and only requests that invoke the script are billed at Workers rates. Each version accepts up to 20,000 asset files on the Free plan and 100,000 on paid plans, with a 25 MiB ceiling per file. Custom Domains require an active Cloudflare zone; unlike Pages, Workers cannot attach a hostname whose nameservers Cloudflare does not manage.
SPA Fallbacks, Real 404s, Headers, and Redirects
Fallback policy is a single string that decides what a wrong URL means to a reader and to a crawler.
| Setting | Value | What the reader gets | Choose it when |
|---|---|---|---|
not_found_handling | "none" (default) | A bare 404 with no body you control | You have no custom 404 page and no client-side router |
not_found_handling | "404-page" | The nearest 404.html in the directory tree, with a real 404 status | Documentation, marketing sites, anything where a wrong URL should stay wrong |
not_found_handling | "single-page-application" | index.html with 200 for requests that match no asset, so a client-side router can resolve the path | Every URL under that hostname is genuinely an application route |
html_handling | auto-trailing-slash (default) | /foo.html redirects 307 to /foo, and /folder maps to folder/index.html | You want one canonical form and can accept the extra hop |
html_handling | "none" | /foo.html is served directly with 200, with no redirect and no directory-index mapping | A generator with stable file-based URLs whose links carry the extension |
The generated documentation site needs 404-page; SPA mode is a defect. A mistyped article URL would return 200 with the home page, and search engines would treat the duplicate as real content. For the settings screen, the reverse is true.
html_handling: "none" stops inventing redirects. On a site whose internal links all end in .html, the default converts every internal navigation into two requests. The trade is that folders no longer resolve to their index file, so the choice must match how the site was built rather than how it looks.
Headers follow the same asset-first rule. A matching static response carries its own content type, an ETag derived from the file, and a cache status recording hit or miss.
The default policy is revalidate-always. For requests with no authorization or range header, Cloudflare adds Cache-Control: public, max-age=0, must-revalidate, which is why a fresh deploy usually appears immediately: the browser revalidates and gets a new ETag.
You override defaults with a _headers file in the asset directory — a path line, then indented name/value lines. Rules merge when several match, up to 100 rules, with a 2,000-character limit per line, and a leading ! removes a header a broader rule added.
_headers stops at the Worker
_headers and _redirects apply only to asset responses — never to anything your Worker returns. That single rule explains the production surprise later in this section.
Redirects are resolved before assets. A redirect can therefore shadow a real file: its 2,000 static and 100 dynamic entries are applied top-down, first match wins, and a 200 entry proxies to a relative path rather than redirecting.
A composite scenario, assembled from documented behavior rather than a measured incident. A team moves a marketing site from Pages to an SSR Worker, carrying over a _headers file whose wildcard block sets Content-Security-Policy and frame options. The build is green, pages render, and the security review passes on a preview URL. In production the headers are absent from every HTML response, because those responses now come from the Worker — and the reviewer had checked a static page. The fix is to attach the headers in the Worker or move them to a zone-level Transform Rule, not to add another asset-header rule.
A tab is not curl
Setting a fallback changes which requests invoke your Worker. With a compatibility date of 2025-04-01 or later, a browser navigation to an unmatched path is answered by the fallback rather than your script.
So a typed API URL can show your 404.html or SPA shell while a fetch from the same page returns JSON. If an API path must work in a tab, cover it with run_worker_first.
That asymmetry is deterministic, not a bug. Navigation requests carry Sec-Fetch-Mode: navigate, and Cloudflare uses that signal to avoid billing an invocation for every page view — which is why the /api/* pattern exists: it makes the endpoint behave the same in a tab, in curl, and in client code.
Pages Compatibility and Migration Decisions
Pages still runs production sites, and the two products are close enough that a migration looks like a configuration rename. It is a precedence change with a few hard boundaries.
Start with the recommendation rather than the feature list. Cloudflare's own Pages documentation now opens by asking whether you are sure, states that Workers supports most Pages use cases with a broader feature set, calls Workers its primary application platform, and tells readers to start new projects with Workers. For a new static or full-stack site, that settles the default: use Workers with static assets. Existing Pages projects do not need to move on a schedule, and a working project with no unmet need is a valid reason to stay.
Figure 4 lines up the two models. The build output crosses over almost unchanged; the behavior around it does not. Pages served Functions ahead of static assets, while Workers serves static assets ahead of the script, so any Pages project relying on middleware, authentication, or request logging needs run_worker_first — and that decision is billed as normal Worker invocations.
The second row is the other common surprise. Pages inferred SPA or 404 behavior from the presence of index.html and 404.html, whereas Workers requires the choice to be explicit.
The mechanical steps are short. Five mappings cover almost every Pages project.
| Pages | Workers | Watch for |
|---|---|---|
pages_build_output_dir | assets.directory, plus name and compatibility_date | The build output itself moves over unchanged |
Advanced-mode _worker.js | Move it out of the asset directory, or list it in .assetsignore | Otherwise it ships as a public file |
functions/ folder | Build with wrangler pages functions build --outdir=./dist/worker/, then point main at the output | The command remains available; new file-based routing work is better done in a framework |
| Build-time and runtime variables | Re-create them as Worker variables and secrets | Pages and Workers keep separate sets |
wrangler pages dev on 8788 | wrangler dev on 8787 | The port changes |
Domains carry the sharpest edge. A Custom Domain cannot attach to a hostname that already has a CNAME record, and a live Pages custom domain holds exactly that claim. The practical order is: deploy the Worker, verify it on workers.dev and on a Version URL, remove the domain from the Pages project, attach it to the Worker, then watch traffic before deleting anything. Workers also refuses hostnames outside Cloudflare zones, so a Pages project serving an external CNAME needs a different plan, not a different config file.
Routes deserve their own check. A route requires a proxied DNS record and runs the Worker in front of an existing origin; a Custom Domain makes the Worker the origin. On the same hostname a route takes precedence — useful for putting a logging Worker in front of an application Worker, dangerous when an old route is left behind.
Overlapping claims produce no error at request time. Confirm ownership in Domains & Routes and prove which Worker answered with a version header rather than guessing from behavior. And remember that workers.dev stays a live hostname unless you disable workers_dev.
Previews are the last parity gap to plan for. Pages creates a preview environment per project; Workers uses a previews block with preview URLs enabled, or a Version URL from npx wrangler versions upload when you only need to inspect one build. Version URLs are public when enabled, inherit the version's configuration, and are the cheapest way to compare an exact build. Branch Previews add per-branch bindings and need Wrangler 4.135.0 or later at the time of writing.
Deploy a Pagegen Build as Worker Static Assets
This exercise deploys a generated series page — the same HTML this repository's build produces — as a Worker with one JSON endpoint, then breaks it in four controlled ways.
Deploy a Pagegen Build as Worker Static Assets
Status: design-only — not executed for this draft. Commands and expectations follow the documentation cited at the end, read on 2026-11-05. No deploy was run, so no latency, cache-hit ratio, or cost figure below is measured.
| Setup | Value |
|---|---|
| Prerequisites | Cloudflare account, Node.js 20 or later, npm, a terminal, and npx wrangler whoami showing the intended account |
| Domain step only | A hostname in an active Cloudflare zone; the Free plan is sufficient and no paid feature is required |
| Inputs | index.html, 404.html, pages/series/cloudflare/*.html, plus css/, js/, images/, feeds/ |
| Config | The wrangler.jsonc from the widget above, a src/index.ts, and a disposable Worker name such as pagegen-lab-<initials> |
Publish, then stage the allowlist.
python3 -m pagegen series publish --manifest content/expanding_series/cloudflare/_manifest.json --topic workers-static-assets-pages-and-app-routing --content-dir content --series-dir content/expanding_series/cloudflare --hub-md content/expanding_series/cloudflare/hub.md --section-id parts
# Confirm the page exists under pages/series/cloudflare/, then stage only
# deployable files into dist/:
# index.html 404.html robots.txt sitemap.xml pages/ css/ js/ images/ feeds/
An asset directory is public by definition, so source folders, version-control metadata, and every Markdown file stay out.
| Step | Action | Expected result |
|---|---|---|
| 1 | Add dist/_headers from the widget above, copy the config with a new name and no routes block, and create src/index.ts | The three files exist; nothing is deployed yet |
| 2 | Run npx wrangler types, then npx wrangler dev | On http://localhost:8787, / and a deep .html page return 200 text/html; /api/health returns 200 application/json; /no-such-page.html returns 404 with the body of 404.html |
| 3 | Run npx wrangler deploy and repeat the same requests against the printed workers.dev URL | ETag and the revalidating cache header on HTML; CF-Cache-Status: MISS on the first request, typically HIT on a repeat |
| 4 | Run npx wrangler versions upload and open the returned Version URL | The deep link and the API behave as in production before promotion |
| 5 | Optional: add the routes entry with custom_domain: true for a hostname you control, deploy, confirm, then remove and redeploy | The same responses as the workers.dev hostname |
Break it four ways, on purpose.
| Failure check | Change | Expected observation |
|---|---|---|
| A — asset shadowing | Add dist/api/health containing the word shadow, remove run_worker_first, redeploy, then curl -i the endpoint | 200 with shadow and no JSON: the shelf answered. Restore ["/api/*"], redeploy, and confirm JSON returns |
| B — fallback instead of API | Remove run_worker_first again, redeploy, open /api/health in a browser tab, and curl -i the same URL | The tab shows 404.html; curl returns JSON, because only the tab sends Sec-Fetch-Mode: navigate. Restore the pattern |
| C — wrong fallback | Set not_found_handling to "single-page-application", redeploy, request a nonexistent page | 200 with the home page instead of 404. Correct for an SPA, wrong for documentation; revert |
| D — headers that do not travel | curl -I an HTML page and the API path | X-Content-Type-Options on the HTML, absent on the JSON, because _headers applies only to asset responses |
A correct run reproduces every branch: asset-first serving, 404-page behavior at real 404 status, JSON only on the API paths, and the four failures exactly as described. Each failure is reversible by configuration alone — no rebuild of the site is needed.
Only script invocations bill. Static asset requests are free and unlimited with no separate storage charge; the Free plan includes 100,000 requests per day with 10 ms CPU per invocation. Because worker-first routing is enabled, exceeding the daily allowance returns 429 for /api/* rather than serving an asset, so a load test can produce a hard failure rather than a degraded one.
Cleanup. Run npx wrangler delete, remove the custom domain, and delete the local build, state, and dev-variable files. If you migrated from Pages, delete that project only after the new hostname has served production traffic.
The failure checks are the deliverable. None of them produces a build error, and none is caught by TypeScript, because every one is a routing-precedence decision that lives in configuration.
Check Deep Links, Real 404s, Asset Types, and Preview URLs
Verification date: 2026-11-05. Basis: the official Cloudflare documentation listed below, read on that date, plus the control flow of the configuration shown above. Execution status: design-only — no Wrangler command was run and no hosted validation was performed; the planning baseline is 2026-11-02. Record your own Wrangler and Node.js versions, compatibility date, and account plan before comparing results.
Pass evidence. A correct deployment shows all of the following.
- A deep link such as
/pages/series/cloudflare/first-worker-wrangler-bindings-and-secrets.htmlreturns200,content-type: text/html, anETag, andCache-Control: public, max-age=0, must-revalidate. - A nonexistent page returns
404with the body of404.htmland does not return the home page. /api/healthreturns200 application/json;/api/unknownreturns404 application/json, never HTML.- A hashed JavaScript file returns
content-type: text/javascriptorapplication/javascript, nottext/html. curl -Ishows the_headersvalues on HTML and not on the Worker's JSON.npx wrangler versions uploadreturns a Version URL that matches production behavior for the same build.
Fail signatures and their causes.
200 text/htmlon an API path means the fallback answered: either the Worker never ran, or the handler returnedenv.ASSETSfor a path it should own.- A
307chain on every internal link meansauto-trailing-slashis rewriting.htmlURLs; choosehtml_handling: "none"for file-based output. 404on every deep link with a correct build meansnot_found_handlingis unset for an SPA, or the files were never indist/.429on/api/*while HTML still serves means the free request allowance is exhausted andrun_worker_firstis doing exactly what it promises.- A missing security header in production but present in a local
curlusually means the response now comes from the Worker, where_headersdoes not apply. - A correct page under a fresh deployment timestamp but old content means a stale worktree or the wrong
--env, not a cache problem; compare the deployed version with the response you are inspecting.
Self-check. Answer before reading the explanations.
- Why does a Worker with
assets.directoryand nomainstill return a 404 for unknown paths? With no script there is nothing to invoke, and the defaultnot_found_handlingisnone, so an unmatched request has no fallback to serve. - If unmatched requests already reach the Worker, what does
run_worker_firstadd? Precedence. It runs the script before the asset lookup, so a file can no longer shadow a path you intended to own, and middleware can act before any asset is served — at the cost of a billable invocation per matched request. - Why can the same URL return JSON from
curland HTML from a browser tab? Navigation requests carrySec-Fetch-Mode: navigate. Withnot_found_handlingset and a compatibility date of 2025-04-01 or later, those requests go to the fallback instead of the script unlessrun_worker_firstcovers the path. - When is
single-page-applicationthe wrong fallback? Whenever some URLs are real documents. It converts every miss into200 index.html, so broken links and duplicate content look healthy to crawlers and to uptime checks.
Unresolved limitations. The exercise was not executed, so no cache-hit, latency, or cost measurement is claimed. The documentation scopes the SPA fallback to navigation requests, but teams should pin the behavior for non-navigation asset misses — a missing hashed chunk — with their own test rather than assuming a 404.
Range requests are a known gap. Assets return 200 with the full file and no Content-Range, which breaks some video playback until the path is routed through the Worker. Branch Previews are newer than Version URLs and require a specific Wrangler version; plan limits, file counts, and pricing change, so re-check them at writing time. The Pages-to-Workers compatibility matrix still has partial cells, so a migration plan should test the specific features a project depends on rather than trusting the summary.
Authoritative references.
- Workers Static Assets
- Static assets billing and limitations
- Configuration and bindings
- Single Page Application routing
- SSG and custom 404 pages
- HTML handling
- Headers
- Redirects
- Migrate from Pages to Workers
- Wrangler configuration
- Custom Domains
- Routes
- Version URLs
- Previews
- Workers limits
- Cloudflare Pages
Next in the Series
In Test Workers and Release Changes Safely, we'll explore Separate local confidence from hosted integration evidence.