In a Cloudflare Worker with static assets, which requests run the Worker's fetch handler and which are served straight from assets.directory?
answer
- files before code
- a miss is what wakes the Worker
- matching files are free requests
- env.ASSETS.fetch() for the rest
basics
~20 sBy default, a request whose path matches a file in assets.directory is served as that file without running the Worker. Only a miss invokes the fetch handler, which can answer itself or hand the request back with env.ASSETS.fetch().
solid answer
~40 sBy default a Worker with static assets is **asset-first**. Wrangler uploads everything in `assets.directory` at deploy, and a request that matches one of those files gets the file directly: the Worker's `fetch` handler never runs, and the request is free and not billed as a Worker invocation. Only a request that matches no file reaches the Worker, if the config has a `main` script; without one the miss gets a 404. Inside the Worker, an optional binding such as `"binding": "ASSETS"` exposes `env.ASSETS.fetch()`, which takes a `Request`, `URL` or string, matches on the pathname only, and applies the `html_handling` and `not_found_handling` settings. `run_worker_first` is the switch that reverses the order.
code
javascript · 12 linesexport default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname.startsWith("/api/")) {
return Response.json({ from: "worker", path: url.pathname });
}
if (url.pathname === "/via-binding") {
return env.ASSETS.fetch(new URL("/assets/app.js", request.url));
}
return new Response("worker:" + url.pathname, { status: 404 });
},
};go deeper
Recall the default order: a matching file is served without the Worker, and only a miss runs fetch. Know that assets.directory names the folder and the binding gives env.ASSETS.fetch().
Explain how html_handling resolves /about to about.html before a miss is declared, that the binding applies the same routing settings, and why a binding without main is rejected.
Show you can predict which code path a URL takes, test it with wrangler dev, and spot code that assumes it sees every request, such as logging or auth at the top of fetch.
Connect the asset-first default to cost: served files are free, invocations are billed, so a team should keep code off the asset path unless a requirement such as auth justifies run_worker_first.
## What a Worker with static assets is A **Worker with static assets** is one Worker deployment that carries two things: a folder of files (HTML, CSS, JavaScript bundles, images, fonts) and, optionally, a script. The Wrangler configuration names the folder with `assets.directory`, usually the build output of a front-end tool such as `./dist`. When you run `wrangler deploy`, Wrangler uploads the files and the script together as one version, and Cloudflare serves the files from its network and caches them close to users. ```json { "name": "spa-move", "main": "src/index.js", "compatibility_date": "2026-10-10", "assets": { "directory": "./dist", "binding": "ASSETS" } } ``` Only one collection of assets can be configured per Worker. ## The default order: files first Routing follows a fixed order unless you change it: 1. If the request path matches a file in the assets directory, that file is served. The Worker's `fetch` handler is **not invoked**. 2. If nothing matches and the config has a `main` script, the Worker runs. 3. If nothing matches and there is no script, the response is a `404 Not Found`. Path matching is a little smarter than an exact filename comparison: the `html_handling` setting (default `auto-trailing-slash`) lets `/about` find `about.html` and `/docs/` find `docs/index.html`, and redirects the other spellings with a `307`. And the `not_found_handling` setting can turn a miss into a fallback page instead of a trip to the Worker; that is the subject of its own question. ## Why the order matters - **Cost.** Requests served from static assets are free and unlimited, and storing assets costs nothing extra. A request that runs the script is billed at normal Workers rates. An app where most traffic is bundles and images pays for the API calls only. - **Latency and limits.** A file served directly runs none of your code, so it uses none of the Worker's CPU time. - **Surprises.** Code in the Worker does not see requests for files that exist. A logging line or an auth check written at the top of `fetch` silently skips every asset. If you need code to run before assets, that is what `run_worker_first` is for. ## The assets binding Adding `"binding": "ASSETS"` (the name is yours to choose) gives the script an object at `env.ASSETS` with one method, `fetch()`: - It accepts a `Request`, a `URL` or a URL string. - Only the **pathname** selects the asset; the hostname is ignored, so `new URL("/logo.svg", request.url)` or `https://assets.local/logo.svg` both work. - It applies `html_handling` and `not_found_handling`, so forwarding a missed request with `env.ASSETS.fetch(request)` returns whatever fallback the config defines. - It returns a `Promise<Response>` like any `fetch`, so the script can change headers or stream the body through another transform before returning it. The binding is only valid with a script. A config that sets `assets.binding` but has no `main` fails in Wrangler with `Cannot use assets with a binding in an assets-only Worker.`, because there is no code to hold the binding. ## Assets-only Workers A Worker can also be **assets-only**: no `main`, just `assets.directory`. That suits a purely static site. Misses then return a 404, or whatever `not_found_handling` says. ## Defaults and limits worth knowing | Item | Value | | --- | --- | | Files per Worker version | 20,000 on Workers Free, 100,000 on Workers Paid | | Size of one file | 25 MiB | | Default `Cache-Control` on an asset | `public, max-age=0, must-revalidate`, with an `ETag` | | Billing for a served asset | free, not counted as a Worker request | The default `Cache-Control` lets browsers keep a copy but revalidate it on every use, so a new deploy is visible immediately; a `_headers` file in the assets directory can set longer lifetimes for content-hashed bundles. ## Checking it locally `wrangler dev` runs the same routing on your machine: request a file that exists and the Worker's `console.log` stays silent; request a path that does not exist and the handler runs. That is the quickest way to show a teammate which code path a URL takes. ## Mistakes that follow from the default - **Putting server-only files in the directory.** Everything in `assets.directory` is public. Configuration, source maps you meant to keep private, or a server script left in the build output are downloadable by anyone who guesses the path. - **Expecting code to guard a file.** An auth check in `fetch` cannot protect a file that exists, because the request never reaches it. - **Reading a 404 as a missing route.** In an assets-only Worker, a 404 means no file matched; there is no script to blame.
- A teammate added a request logger at the top of the fetch handler, but CSS and image requests never appear in it. Why?Those paths match files in `assets.directory`, so they are served by the asset layer and the Worker is never invoked; there is nothing for the logger to see. To run code on every request, set `assets.run_worker_first` to `true` (or to route patterns) and return files through `env.ASSETS.fetch(request)`. Expect those requests to become billed invocations.
- Does the hostname matter in a URL passed to env.ASSETS.fetch()?No. Only the pathname is used to find the asset, so any valid hostname works, which is handy inside an RPC method that has no incoming request: `env.ASSETS.fetch("https://assets.local/manifest.json")`. The binding still applies `html_handling` and `not_found_handling` to that path.
A library's open shelves and its help desk: if the book you want is on the shelf you take it without speaking to anyone, and only a request for something not on the shelves goes to the librarian, who may still walk you back to a shelf.
- The Worker's fetch handler runs for every request, including image and script files
- Static asset requests are billed as Worker requests
- env.ASSETS.fetch() needs the Worker's own hostname to find the file
- An assets-only Worker can still declare an assets binding
- Wrangler uploads assets in a separate deploy step from the Worker script