Skip to content
James Ross
articlePublished Updated 8 min read

When a Worker never runs: static assets and run_worker_first

By James Ross

A browser navigation to an on-demand Astro route on Cloudflare Workers returned the static 404 page without invoking the Worker, while a fetch() to the same URL reached the Worker and returned 200. The fix was to generate assets.run_worker_first from Astro's resolved route table: 36 patterns on one site, 33 on another, covered by 8 unit tests.

A request path forking between a static file shelf and a dark compute node with an amber switch, showing the run_worker_first setting.

The same edge platform serves the WordPress-to-Workers fleet, and this is the failure mode that appears once a site on it has routes that render at request time: static pages are fine, and every on-demand page disappears only when a human clicks a link.

What does run_worker_first actually change?

run_worker_first decides whether the Worker script runs before Cloudflare checks for a matching static asset. By default the asset layer answers first, and the Worker only runs when nothing matches. Setting run_worker_first to an array of paths flips that order for the listed paths only.

The setting lives under assets in the Wrangler configuration:

{
  "assets": {
    "directory": "./dist/",
    "binding": "ASSETS",
    "not_found_handling": "404-page",
    "run_worker_first": ["/lookup", "/lookup/", "/number/*"]
  }
}

Three behaviours matter in production:

  • A matching path invokes the Worker first, every time, even if an asset exists at that path.
  • A non-matching path keeps the asset-first order, so static pages stay on the fast path.
  • Negative patterns (!/assets/*) take precedence over positive ones, which is how you keep a large static tree out of the Worker.

The list is not a routing table with priorities. Order does not matter, duplicates count against the 100-entry cap, and a pattern that is already covered by a prefix wildcard is rejected as redundant by Wrangler at deploy time.

Why did fetch() work while the browser got a 404?

The browser sends Sec-Fetch-Mode: navigate on a page load, and Cloudflare treats that request differently from a fetch() call. When not_found_handling is configured and the compatibility date is 2025-04-01 or later, a navigation request that matches no asset is answered from not_found_handling without invoking the Worker.

That is a deliberate cost optimisation: navigation requests are a large share of traffic, especially on a client-rendered site, and invoking a Worker for each one is billable. Cloudflare’s own docs describe the surprising result: navigate to an API path in a browser and you get HTML, while fetch() from the page gets the API response (Cloudflare docs).

For a hybrid Astro site, the effect is worse than surprising. Prerendered pages exist as assets, so they are served correctly. On-demand pages do not exist as assets, so a navigation gets the 404 page. The same URL fetched by a test script reaches the Worker, renders the page and returns 200. Every automated check passes while every human visitor sees a 404.

The routing diagram in Cloudflare’s docs is worth reading once: request, run-worker-first check, asset match, Worker present, navigation request, asset serving, not_found_handling. The branch that bit this deployment is the one labelled “request is navigation request”.

Which routes were failing?

The affected sites had a small static core and a handful of request-time routes:

  • a lookup page that reads a query string and renders results;
  • dynamic number pages, one per record, generated on demand;
  • POST /api/contact and the newsletter endpoints;
  • a newsletter confirmation page.

All of them worked in local development and in wrangler dev. The pages failed in production when reached by a browser navigation, while the API endpoints were fine when called with fetch() from the page. That is exactly why the contact form worked while the lookup page did not.

Why did wrangler dev not reproduce it?

wrangler dev serves requests through the Worker and its local asset layer, but it does not exercise the deployed asset router’s navigation shortcut. The request that production short-circuits never reaches the local Worker, so local behaviour is not evidence about production routing.

This is the practical lesson from the incident: routing behaviour that lives in the edge platform has to be tested at the edge. A local server, a unit test and a fetch() smoke test can all pass while the browser path is broken. The verification that matters is a request with the navigation header against the deployed URL:

curl -s -o /dev/null -w '%{http_code}\n' \
  -H 'Sec-Fetch-Mode: navigate' \
  https://example.com/lookup

Run it with and without the header. If the two differ, the asset router is making a decision the Worker never sees.

How do you generate run_worker_first from Astro’s routes?

The route list cannot be maintained by hand. On-demand routes change as pages are added, and a missed pattern is a 404 that only humans see. The durable fix is an Astro integration that reads the resolved route table at build time and writes the patterns into the generated Wrangler config.

Astro exposes the route table through the astro:routes:resolved hook and the build output through astro:build:done (Astro Integration API). The integration does five things:

  1. Collect every route whose prerender flag is false.
  2. Convert each route’s segments into a glob: a static segment keeps its text, a dynamic segment becomes *, and a spread segment ends the pattern with *.
  3. Add a trailing-slash variant for static routes, because /lookup and /lookup/ are different patterns.
  4. Drop any pattern already covered by a prefix wildcard, which is what Wrangler rejects as redundant.
  5. Write the surviving patterns into assets.run_worker_first in the generated wrangler.json during astro:build:done.

A reduced version of the conversion:

export default function workerFirst() {
  const patterns = new Set();
  const toGlob = (segments) => '/' + segments.map((seg) => {
    if (seg.spread) return '*';
    return seg.dynamic ? '*' : seg.content;
  }).join('/');
  return {
    name: 'worker-first',
    hooks: {
      'astro:routes:resolved': ({ routes }) => {
        for (const r of routes.filter((r) => !r.prerender)) {
          const glob = toGlob(r.segments);
          patterns.add(glob);
          if (!glob.endsWith('*')) patterns.add(glob + '/');
        }
      },
      'astro:build:done': async ({ dir }) => {
        const file = new URL('server/wrangler.json', dir);
        const config = JSON.parse(await readFile(file, 'utf8'));
        config.assets.run_worker_first = pruneCovered(patterns);
        await writeFile(file, JSON.stringify(config, null, 2));
      },
    },
  };
}

The sketch omits the bookkeeping: normalising double slashes, keeping / out of the list, and the pruneCovered pass that removes /blog/post when /blog/* already matches it. That pass is not cosmetic. Wrangler refuses a rule it considers redundant, so without it the deploy fails on a config the integration just wrote.

How do you verify the generated list?

Three checks catch most of the mistakes:

  1. Count the patterns and compare with the route count. The build printed 36 patterns for one site and 33 for the other. A number far above the route count means duplicates; a number below it means skipped routes.
  2. Grep the generated wrangler.json for run_worker_first and read the actual list. The integration writes into the adapter’s output, not the source config, so the source file will not show it.
  3. Request each on-demand route with the navigation header against the deployed URL, then check Workers Logs or observability for an invocation. A 200 with no invocation is a cached asset or a coincidence; a 200 with an invocation is the Worker doing the work.

The eight tests cover the conversion function rather than the deployment, including the pruning pass where the subtle cases live. That is enough to keep the generator honest as routes are added.

Routing options compared

Configuration Asset match No asset match Worker on navigation Best for
Assets only, no main asset served 404 or not_found_handling never pure static site
Assets plus Worker, no not_found_handling asset served Worker runs yes mixed static and API
not_found_handling: "404-page" asset served 404 page no static site with custom 404
not_found_handling: "single-page-application" asset served index.html no SPA shell
run_worker_first: ["/api/*"] asset served elsewhere Worker runs only on /api/* static site plus API
Generated run_worker_first routes asset served for static pages Worker runs on listed routes yes, for those routes hybrid static and on-demand pages

Which should you choose?

Choose the generated route list when the site is mostly static but a known set of paths renders per request. It keeps the asset path fast for the majority of pages and pays for Worker invocations only where the page needs one.

Choose run_worker_first: true only when every request must pass through the Worker, for example for authentication, logging or HTML rewriting across the whole site. It is the simplest setting and the most expensive one, because no request can be answered by the asset layer alone.

Choose run_worker_first: ["/api/*"] for a static site with an API. It is the configuration this project started with, and it is correct as far as it goes; it simply does not cover server-rendered pages, which is the case that broke.

What broke and what we changed

The failure was invisible to every test that did not use a browser. The smoke tests used fetch(), which bypasses the navigation shortcut, so they returned 200 while visitors got 404s. A deployment check that sends Sec-Fetch-Mode: navigate to every on-demand route is the only test that would have caught it, and that check now belongs in the release gate rather than in a local script.

The first fix was too narrow. Adding /api/* to run_worker_first fixed the form endpoints, which were already working, and did nothing for the lookup pages. The route list had to come from the framework’s route table, not from a guess about which paths looked dynamic.

Wrangler rejected redundant rules. The first generated list contained patterns already covered by a broader wildcard. Wrangler refuses a redundant entry, so the build failed at deploy time rather than at test time. The generator now prunes any pattern covered by an existing prefix wildcard before writing the config.

Trailing slashes were a separate route. /lookup and /lookup/ match different patterns, so a static route needs both variants; a dynamic pattern does not, because the * already matches the slash. A missing variant is the kind of bug that looks like caching, because one URL works and the other does not.

The 100-entry cap is closer than it looks. This fleet generated 36 and 33 patterns, comfortably inside the limit. A site with many static routes that also need Worker-first treatment could cross 100, and then the answer is a broader prefix pattern plus negative patterns, not a longer list. The generator should count entries and fail the build before the platform does.

Frequently asked questions

What is run_worker_first in Cloudflare Workers?

run_worker_first is an assets setting that controls whether the Worker script runs before Cloudflare checks for a static asset. It can be true for every request, or an array of glob patterns for specific paths. On a matching path the Worker runs first and can serve the asset itself through the ASSETS binding; on other paths the asset layer answers first.

Why does my Worker return 404 only in a browser?

Because the browser sends Sec-Fetch-Mode: navigate and Cloudflare treats navigation requests differently. With not_found_handling configured and a compatibility date of 2025-04-01 or later, a navigation that matches no asset is answered with the 404 page without invoking the Worker. A fetch() call lacks that header, reaches the Worker and returns the page.

Does run_worker_first slow down static assets?

It does for the paths you list, because those requests invoke the Worker before the asset layer. Paths outside the list keep the default asset-first behaviour and are unaffected. That is the reason to generate a route list rather than set the flag to true: the cost is confined to the pages that actually need request-time rendering.

How many patterns can run_worker_first take?

At most 100 entries. The limit counts raw entries, so duplicates and patterns already covered by a wildcard still count against it. Wrangler also rejects rules it considers redundant, which is why a generator should prune covered patterns before writing the config rather than appending every route it finds.

Do run_worker_first requests count against the free plan?

Yes. Requests that match a run_worker_first pattern always invoke the Worker and count toward the plan's request allowance. On the free plan, exceeding the daily request limit returns a 429 for those paths instead of falling back to asset serving. Negative patterns are exempt because they are routed straight to assets (Cloudflare docs).

Do prerendered Astro pages need a run_worker_first pattern?

No. Prerendered pages exist as HTML assets, so the asset layer serves them correctly and the Worker is never needed. The generator skips any route whose prerender flag is true, which keeps the list short and keeps static pages on the cheapest path.

Why not set run_worker_first to true and be done?

Because every request then invokes the Worker, including image, font and CSS requests that the asset layer could answer for free. On a content site that is most of the traffic. The flag is the right answer when the Worker must inspect every request, not when a handful of routes render on demand.