skip to content

Workers Static Assets

A Worker can serve a directory of static assets before or after its own code runs. Interviewers ask how not_found_handling serves a single-page app and when run_worker_first is needed.

on this pageshow

explore

questions

6

In a Cloudflare Worker with static assets, which requests run the Worker's fetch handler and which are served straight from assets.directory?

level: juniorimportance: must knowfreq 45%

answer

  1. files before code
  2. a miss is what wakes the Worker
  3. matching files are free requests
  4. env.ASSETS.fetch() for the rest

basics

~20 s

By 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 s

By 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 lines
javascript
export 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

for a junior

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().

for a middle

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.

for a senior

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.

for a principal

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
open as a page

In Cloudflare Workers static assets, how does not_found_handling serve a single-page app, and how do its three values differ?

level: middleimportance: must knowfreq 45%

basics

~20 s

In Workers static assets, not_found_handling sets the reply when no file matches: single-page-application serves /index.html with 200, 404-page the nearest 404.html with 404, and none, the default, an empty 404. With a Worker script and no route patterns, non-navigation misses reach the script first.

open as a page

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%

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.

open as a page

After moving an SPA from Pages to a Cloudflare Worker with single-page-application fallback, the browser's OAuth redirect to /auth/callback returns index.html and never reaches the Worker; why, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

The provider's redirect is a browser navigation carrying Sec-Fetch-Mode: navigate, and for compatibility dates from 2025-04-01 a navigation that misses is answered with the SPA fallback without invoking the Worker. List the route in run_worker_first, or finish the exchange from client-side code.

open as a page

For a team running an SPA and its API on Cloudflare Pages, how would you decide whether and when to move it to a Worker with static assets?

level: principalimportance: should knowfreq 30%

basics

~20 s

Cloudflare now points new projects to Workers with static assets, so new sites start there. An existing Pages app moves when it needs a Workers-only feature or a major rework, unless it relies on a domain outside Cloudflare's nameservers or Pages-only branch controls.

open as a page

When moving a Pages build output to Cloudflare Workers static assets, what happens to its _headers, _redirects and _worker.js files, and what does .assetsignore do?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

Workers static assets read _headers and _redirects from the assets directory as rules, not files, applying them only to asset responses. A Pages _worker.js would become a public file, so wrangler deploy refuses it while no .assetsignore exists: move it out or list it there.

open as a page