skip to content

In Cloudflare Workers static assets, when do you need run_worker_first, and how do its true and route-pattern forms differ?

level: middleimportance: should knowfreq 35%

answer

  1. code before files
  2. auth, logging, rewriting HTML
  3. a boolean or a list of globs
  4. negative patterns win
  5. every match is a billed invocation

basics

~20 s

Use run_worker_first when code must see a request before a matching file is served, such as an auth check. true runs the Worker for every request; an array of route patterns, with ! exclusions, runs it only for matching paths.

solid answer

~40 s

`assets.run_worker_first` defaults to `false`, so matching files bypass the Worker. You need it when code has to run before a file is served: authentication in front of protected assets, logging, A/B tests, or rewriting HTML with `HTMLRewriter`. Set to `true`, every request invokes the Worker, which then returns files through `env.ASSETS.fetch(request)`; without an `assets.binding` Wrangler warns that the Worker cannot reach its assets. As an array (Wrangler 4.20.0 and later), patterns such as `["/api/*", "!/api/docs/*"]` run the Worker first only where a positive pattern matches and no `!/` pattern does; order is irrelevant, at most 100 entries. Every matched request is a billed invocation, and on Workers Free an exhausted daily limit returns `429` for those paths rather than falling back to assets.

code

json · 11 lines
json
{
  "name": "spa-move",
  "main": "src/index.js",
  "compatibility_date": "2026-10-10",
  "assets": {
    "directory": "./dist",
    "binding": "ASSETS",
    "not_found_handling": "single-page-application",
    "run_worker_first": ["/api/*", "/admin/*"]
  }
}

go deeper

for a junior

Recall that the default is false, that true runs the Worker before every request, and that the Worker returns files through env.ASSETS.fetch().

for a middle

Explain the array form: / and !/ prefixes, deep * globs, negatives winning regardless of order, the 100-entry cap, and that it replaces navigation-header routing.

for a senior

Show the production effects: billed invocations for matched paths, 429s on Workers Free after the daily limit, _headers not applying to Worker responses, and placement latency with true.

for a principal

Set a team default of the narrowest pattern list, so code runs only where a requirement such as auth needs it, and review any switch to true for its cost.

## The default it overrides A Worker with static assets is **asset-first**: a request whose path matches a file in `assets.directory` is served without invoking the script. That is cheap and fast, but it means code never sees requests for files that exist. `assets.run_worker_first` in the Wrangler configuration reverses the order, for every request or for chosen paths. It defaults to `false`. ## When you need it - **Authentication in front of files.** An admin bundle at `/admin/panel.js` is a real file, so without this setting anyone can download it whatever the Worker would have said. - **Logging or analytics on every page view**, including views of files that exist. - **Transforming assets**, for example injecting data into `index.html` with `HTMLRewriter`, or adding per-user headers. - **Server routes that a browser navigates to**, such as an OAuth callback, which would otherwise receive the SPA shell under `single-page-application`. - **A migration from Pages** whose Functions or `_middleware` ran ahead of static files; Pages served Functions first, Workers serves assets first. ## The two forms | Form | Worker runs first for | Typical use | | --- | --- | --- | | `true` | every request | auth or rewriting across the whole site | | `["/api/*", "!/api/docs/*"]` | paths matching a positive pattern and no negative one | API and a few server routes beside an SPA | Rules for the array form, which needs Wrangler 4.20.0 or later: 1. Each entry starts with `/` or `!/`; anything else is rejected. 2. `*` matches deeply, so `/api/*` covers `/api/v1/users/7`. 3. A `!/` pattern wins over positive ones, and the order of entries does not matter. 4. At least one positive pattern is required, and at most 100 entries are allowed, with duplicates counted. 5. With an array, the browser's `Sec-Fetch-Mode: navigate` header no longer decides anything: matching paths go to the Worker even on navigation, and other misses get the `not_found_handling` fallback without invoking code. ## Fetching files from a Worker that runs first Once the Worker runs first, the asset layer no longer answers on its own for those paths. The Worker returns files through the binding: `env.ASSETS.fetch(request)` serves the matching asset and, on a miss, applies `not_found_handling`. Configure `"binding": "ASSETS"` (any name) alongside; Wrangler warns `run_worker_first=true set without an assets binding` when it is missing, and refuses `run_worker_first` entirely when there is no `main` script. ```javascript export default { async fetch(request, env) { const url = new URL(request.url); const signedIn = await hasSession(request, env); if (url.pathname.startsWith("/admin/") && !signedIn) { return Response.redirect(new URL("/login", url), 302); } return env.ASSETS.fetch(request); }, }; ``` ## What it costs - **Billing.** Served assets are free; a request that runs the Worker is billed like any invocation, including those that end in `env.ASSETS.fetch()`. With `true`, a site's entire traffic becomes billable. - **Workers Free limits.** When the daily request limit is used up, requests matching the patterns get `429 Too Many Requests`, not the static file. Negative patterns keep serving assets without the Worker. - **Headers.** Rules in `_headers` apply to responses served from assets, not to a `Response` the script builds, so security headers on Worker-generated pages belong in code. - **Placement.** With Smart Placement and `true`, every asset request first travels to wherever the Worker was placed, and Wrangler warns about the added latency. ## Choosing between the forms Prefer the narrowest array that covers the paths needing code. `true` is right when the code genuinely applies everywhere, such as a site behind a login, and wrong when it exists to serve a dozen API routes. ## Testing the routing before deploy `wrangler dev` applies `run_worker_first` the same way, so the routing can be checked with a handful of requests before anything ships: - Request a protected file, such as `/admin/panel.js`, without a session and confirm the Worker's redirect or `401` arrives instead of the file. - Request a path covered by a `!/` exclusion and confirm it is served without a log line from the Worker. - Navigate to an unmatched client route and confirm the SPA shell arrives without invoking code. - Request a file outside every pattern and confirm it still bypasses the Worker. Writing these as a short smoke test in CI catches the common regression, a pattern edited so that it no longer covers a protected path.

  • Why does a run_worker_first array need at least one positive pattern?
    Negative `!/` patterns only carve exceptions out of paths that would otherwise run the Worker first. A list of exceptions alone selects nothing, so Wrangler rejects it with an error saying only negative rules were provided. If you want no Worker-first paths, leave `run_worker_first` unset.
  • A page served through run_worker_first is missing the security headers listed in _headers. Why?
    `_headers` rules apply to responses served from static assets. A `Response` built by the script, such as a server-rendered page or JSON, does not get them, so the Worker has to set those headers itself. A file returned through `env.ASSETS.fetch()` is still an asset response, so check where the HTML actually came from.

  • run_worker_first defaults to true once a main script is configured
  • Patterns in a run_worker_first array are matched in order, first match wins
  • Requests that end in env.ASSETS.fetch() are free because they return a static file
  • With run_worker_first set to true, matching files are still served without invoking the Worker
  • A run_worker_first array may contain only !/ exclusion patterns

Assumes Wrangler 4: run_worker_first accepts an array of route patterns from Wrangler 4.20.0; earlier releases took only a boolean.