Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Static Asset Routing, Bindings, HTML Handling, and SPA Fallback

How Workers Static Assets route requests, use the ASSETS binding, and configure SPA fallbacks, trailing slashes, and path prefixes.

This page summarizes Cloudflare Workers Static Assets documentation: hosting HTML, CSS, JavaScript, and media with a Worker, configuring request routing in Wrangler, and combining static files with API logic through the ASSETS binding.

Default static asset routing: asset-first vs Worker script

Section titled “Default static asset routing: asset-first vs Worker script”

By default, Cloudflare tries to match the request path against a file in your uploaded asset directory (assets.directory in Wrangler, or the client build output when you use the Cloudflare Vite plugin). If a file matches, it is served without running Worker code. If nothing matches and a Worker entry (main) exists, the Worker runs; it can return a response or defer to assets via env.ASSETS.fetch(request). With no Worker, behavior falls back to not_found_handling.

By default, if a requested URL matches a file in the static assets directory, that file will be served — without invoking Worker code. If no matching asset is found and a Worker script is present, the request will be processed by the Worker. The Worker can return a response or choose to defer again to static assets by using the assets binding (e.g. env.ASSETS.fetch(request)). If no Worker script is present, a 404 Not Found response is returned.

— Cloudflare, Static Assets

On Cloudflare Pages, HTML routes and SPA detection were more implicit; on Workers you set SPA vs custom 404 behavior explicitly in Wrangler (see migrate from Pages).

Wrangler assets configuration: directory, binding, and limits

Section titled “Wrangler assets configuration: directory, binding, and limits”

Configure static hosting under the assets key in your Wrangler configuration. You can configure one asset collection per Worker.

Option Purpose
directory Folder of files Wrangler uploads (e.g. ./dist, ./build, ./public). Optional with the Vite plugin; build output is inferred.
binding Name on env (commonly ASSETS) to fetch assets from Worker code; only when main is set.
base_path URL prefix for assets (default /); files stay at the root of directory. Requires Wrangler 4.148.0+.
run_worker_first false (default), true, or up to 100 route patterns (*, ! exceptions).
html_handling Trailing-slash canonicalization for HTML (auto-trailing-slash default).
not_found_handling none, single-page-application, or 404-page.

Static assets allows developers to run front-end websites on Workers. You can configure the directory of assets, an optional runtime binding, and routing configuration options.

— Cloudflare, Wrangler configuration — Assets

For assets-only sites, omit main and usually omit binding (binding requires a Worker script). See Workers best practices and framework guides such as Astro (static) or Docusaurus.

Excluding files from upload: .assetsignore

Section titled “Excluding files from upload: .assetsignore”

Place a .gitignore-format .assetsignore in the asset directory root so Wrangler skips paths like _worker.js, _redirects, or _headers when migrating from Pages.

env.ASSETS.fetch(): programmatic static asset serving

Section titled “env.ASSETS.fetch(): programmatic static asset serving”

When assets.binding is set, the binding behaves like a fetcher to your asset collection—similar to a Service binding.

The env.ASSETS.fetch() function allows you to fetch a static asset from your Pages project.

You can pass a Request object, URL string, or URL object to env.ASSETS.fetch() function. The URL must be to the pretty path, not directly to the asset. For example, if you had the path /users/index.html, you will request /users/ instead of /users/index.html. This method call will run the header and redirect rules, modifying the response that is returned.

— Cloudflare, Pages Functions API reference

The same pattern applies on Workers: requests through the binding apply html_handling and not_found_handling. Only the URL pathname matters; any valid hostname works (e.g. https://assets.local/...).

Typical full-stack pattern from Static Assets:

export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname.startsWith("/api/")) {
return new Response(JSON.stringify({ name: "Cloudflare" }), {
headers: { "Content-Type": "application/json" },
});
}
return env.ASSETS.fetch(request);
},
};

FastAPI and Flask on Workers often set run_worker_first: true so API routes win, then proxy unmatched paths to ASSETS.

not_found_handling: SPA fallback vs custom 404

Section titled “not_found_handling: SPA fallback vs custom 404”

Choose how unmatched routes behave after asset matching fails.

single-page-application (client-side routing)

Section titled “single-page-application (client-side routing)”

For SPAs (React, Vue, Svelte, etc.), set not_found_handling to single-page-application. Unmatched requests are rewritten to /index.html with 200 OK—required for client routers.

Configuring assets.not_found_handling to single-page-application overrides the default serving behavior of Workers for static assets. When an incoming request does not match a file in the assets.directory, Workers will serve the contents of the /index.html file with a 200 OK status.

— Cloudflare, Single Page Application (SPA)

Framework + Vite examples: React + Vite, Foldkit SPA.

For static sites with real 404 pages, use 404-page. Workers serves the nearest 404.html with 404 Not Found (see Static Site Generation and custom 404 pages).

Astro example from Astro on Workers:

{
"assets": {
"directory": "./dist",
"not_found_handling": "404-page"
}
}
Section titled “Navigation requests (Sec-Fetch-Mode: navigate)”

With a Worker + not_found_handling and compatibility date 2025-04-01 or later (or assets_navigation_prefers_asset_serving), browser navigations often skip the Worker and use asset/SPA rules—reducing billable invocations. Client fetch("/api/...") still hits the Worker; typing /api/... in the address bar may return HTML. Override with assets_navigation_has_no_effect, or use explicit run_worker_first patterns (SPA routing, Worker script routing).

run_worker_first: middleware, APIs, and selective SPA control

Section titled “run_worker_first: middleware, APIs, and selective SPA control”

run_worker_first controls whether the Worker runs before static matching.

Value Behavior
false (default) Matching static files are served first.
true Worker runs on every request; use env.ASSETS.fetch(request) to serve files (auth, logging, HTMLRewriter).
string[] Worker runs first only when a pattern matches; ! patterns except paths. Negative patterns take precedence; order does not matter. Max 100 entries (duplicates count).

Controls whether to invoke the Worker script regardless of a request which would have otherwise matched an asset. run_worker_first = false (default) will serve any static asset matching a request, while run_worker_first = true will unconditionally invoke your Worker script.

— Cloudflare, Configuration and Bindings

Array routing needs Wrangler v4.20.0+ and Cloudflare Vite plugin v1.7.0+ (changelog — SPA routing control). Example: API first, static docs excepted:

[assets]
directory = "./dist/"
not_found_handling = "single-page-application"
binding = "ASSETS"
run_worker_first = [ "/api/*", "!/api/docs/*" ]

This opts out of implicit Sec-Fetch-Mode routing when you need explicit paths (React + Vite — asset routing). For injecting bootstrap data into index.html, see SPA shell with bootstrap data (run_worker_first: ["/*", "!/assets/*"] is a common pattern).

html_handling: trailing slashes and canonical HTML URLs

Section titled “html_handling: trailing slashes and canonical HTML URLs”

assets.html_handling sets redirects/rewrites for HTML paths (auto-trailing-slash, force-trailing-slash, drop-trailing-slash, none). Default auto-trailing-slash serves file.html without a trailing slash and folder index.html with one—relevant for duplicate-URL concerns described in HTML handling. Advanced topics: gradual rollouts and routing, routing overview.

base_path: serve assets under a URL prefix

Section titled “base_path: serve assets under a URL prefix”

Set assets.base_path (Wrangler) or worker.assets.basePath (cloudflare.config.ts) to mount files under a path without moving them in the build folder (Serving a subdirectory, changelog — base path).

Set assets.base_path to serve static assets from a URL subpath. The files remain at the root of assets.directory.

— Cloudflare, Serving a subdirectory

Requests outside the prefix do not resolve those assets. _headers, _redirects, and run_worker_first patterns use the public URL path (include /blog if base_path is /blog). Binding fetches must include the prefix, e.g. env.ASSETS.fetch("https://assets.local/blog/posts/post1").

The Vite plugin static assets reference enables assets when the client build exists (index.html, public/, etc.). vite build writes an output wrangler.json with assets.directory pointed at client output. Put routing flags (not_found_handling, base_path, binding, run_worker_first) in your input Wrangler config. Workers with Static Assets do not receive ctx.access in the user Worker (documented limitation on that page). Tutorial: React SPA with an API.

From To on Workers
Pages pages_build_output_dir assets.directory
Pages implicit SPA (no top-level 404.html) not_found_handling: "single-page-application"
Pages 404.html behavior not_found_handling: "404-page"
Pages Functions default (functions before static) Often run_worker_first: true or path arrays
Pages ASSETS binding Explicit assets.binding: "ASSETS" when using main

Details: Migrate from Pages to Workers. Advanced mode _worker.js becomes main plus return env.ASSETS.fetch(request) and excluding _worker.js from uploads.

Do not start new projects on Workers Sites (site.bucket + KV). It is deprecated in Wrangler v4; use Workers Static Assets instead (Workers Sites, deprecations).

For KV-only asset serving without the Static Assets product, see store and retrieve static assets in KV—Cloudflare recommends Static Assets or Pages for normal web apps.

  • Setting binding: "ASSETS" without main (invalid).
  • Uploading _worker.js or server bundles as public assets—use .assetsignore or move the script (binding — ignoring assets).
  • Calling env.ASSETS.fetch with /path/index.html instead of the pretty path /path/.
  • Expecting the Worker on full-page navigation to /api/* while SPA asset preference is enabled.
  • Wrong directory after migration (./dist vs ./dist/client for SSR stacks; see Foldkit).
  • Using deprecated site config with the Vite plugin (migrating from wrangler dev).
  • Forgetting base_path in binding URLs and in _routes / run_worker_first patterns.
  1. Run your framework build locally and confirm output matches assets.directory (or the generated config from vite build per static assets — Vite).

  2. Deploy with Wrangler (npx wrangler deploy as in Astro static deploy) and open a known static file URL; it should return 200 without unnecessary Worker invocations when run_worker_first is false.

  3. For an SPA, open a deep client route (e.g. /about) in the browser; it should load index.html (200) when not_found_handling is single-page-application (SPA configuration).

  4. Hit an API path with fetch from the app and via direct navigation; compare behavior with your run_worker_first and compatibility flags (Worker script).

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about so it can be corrected.