valfz

Workers from first principles

Static assets

Serve the front end from the same Worker and control which requests are answered from files and which reach your code.

lesson
07 of 08
read
13 min

The shortener needs a page with a form. A Worker can ship static files alongside its code, and Cloudflare serves those files without running the code. The part that needs care is the decision made before your handler runs: which requests are answered from files and which reach fetch. A shortener tests that decision well, because / must be a file and /snw8zr must not be.

Add the front end

public/index.html
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<title>shortlinks</title>
	</head>
	<body>
		<h1>shortlinks</h1>
		<form id="create">
			<p>
				<label>Long URL <input name="url" type="url" required /></label>
			</p>
			<p>
				<label>Token <input name="token" type="password" required /></label>
			</p>
			<button>Shorten</button>
		</form>
		<p id="result" role="status"></p>

		<script type="module">
			const form = document.querySelector("#create");
			const result = document.querySelector("#result");

			form.addEventListener("submit", async (event) => {
				event.preventDefault();
				const { url, token } = form.elements;

				const response = await fetch("/api/links", {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						Authorization: `Bearer ${token.value}`,
					},
					body: JSON.stringify({ url: url.value }),
				});
				const body = await response.json();

				if (!response.ok) {
					result.textContent = `Error ${response.status}: ${body.error}`;
					return;
				}
				const link = document.createElement("a");
				link.href = body.short;
				link.textContent = body.short;
				result.replaceChildren("Short link: ", link);
			});
		</script>
	</body>
</html>
public/404.html
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Link not found</title>
	</head>
	<body>
		<h1>Link not found</h1>
		<p>This short link does not exist or has expired. <a href="/">Create one</a>.</p>
	</body>
</html>

There is no setting that names the assets directory. In a project built with the Cloudflare Vite plugin, the assets are the output of Vite’s client build, and that includes everything in public/.

With the dev server running, open http://localhost:8791/, enter a URL and the token from .dev.vars, and submit. The page calls POST /api/links on its own origin, so no CORS configuration is involved. A token typed into a form suits a tool with one administrator and nothing larger.

Asset first, then the Worker

The default rule has two steps. If the request path matches a file, Cloudflare serves the file and your Worker is not invoked. If nothing matches, the request goes to fetch. Requests answered from assets are free and do not count as Worker invocations (billing and limitations).

Under cf dev the Vite dev server serves the files in public/. The result is close to the platform’s behavior without being identical: /index.html, for one, is answered directly there. To exercise the real router, build the Worker and serve the build output:

pnpm exec cf build
pnpm exec vp preview --port 8794

The preview runs the production-mode build from .cloudflare/output/ with the same local KV and D1 data and the same .dev.vars. It does not watch for changes, so rebuild and restart it after each configuration change in this lesson.

curl -i http://localhost:8794/
HTTP/1.1 200 OK
...
cache-control: public, max-age=0, must-revalidate
cf-cache-status: HIT
content-length: 1316
content-type: text/html; charset=utf-8
etag: "c8277b26f026fa0b5cbb88af679ba032"
...

The caching headers are the platform’s choice for assets. A browser may keep the file but has to revalidate it on every use, and a request that carries the etag back in If-None-Match gets a 304 Not Modified with no body. A new deploy is therefore visible on the next page load, at the price of one conditional request per file.

The explicit file name behaves differently:

curl -i http://localhost:8794/index.html
HTTP/1.1 307 Temporary Redirect
...
location: /
...

That is the default HTML handling: an HTML file is served at its path without the extension, and the .html form redirects there. 404.html is therefore reachable at /404. A short code matches no file and reaches the Worker. Use a code you created with the form:

curl -i http://localhost:8794/snw8zr
HTTP/1.1 302 Found
...
location: https://developers.cloudflare.com/workers/static-assets/
...

The navigation trap

There is a 404.html, and there is a setting that looks made for it. Add it under entrypoint in the configuration:

cloudflare.config.ts
		assets: {
			notFoundHandling: "404-page",
		},

Rebuild, restart the preview and repeat the request. With curl it still redirects. Now send the header a browser adds when the user follows a link:

curl -i -H 'Sec-Fetch-Mode: navigate' http://localhost:8794/snw8zr
HTTP/1.1 404 Not Found
...
content-length: 244
content-type: text/html; charset=utf-8
...

The link exists and the browser gets the 404 page. 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 by the not-found handling and the Worker is never invoked. The single-page application guide documents this, and it is what a client-rendered app wants: every unknown path returns the app shell without a billed invocation. For a Worker whose main job is answering paths that are not files, it breaks every link, and only in browsers. A check with plain curl passes.

"single-page-application" has the same effect with index.html and a 200. Remove the setting. The default, "none", hands every unmatched request to the Worker.

Running the Worker first

runWorkerFirst is the opposite lever. Set it to true and every request goes to your code before any file is considered:

cloudflare.config.ts
		assets: {
			runWorkerFirst: true,
		},
curl -i http://localhost:8794/
HTTP/1.1 404 Not Found
...
content-type: application/json
...

{"error":"not found"}

The route table has no entry for /, so the front page is gone. A Worker that runs first has to serve the files itself, through the assets binding introduced below.

The setting also takes a list of path patterns, and that form is the one this project keeps: runWorkerFirst: ["/api/*"]. It guarantees that a file can never shadow an API route and that API paths are exempt from any not-found handling added later. The cost is stated on the billing page linked above. Matching requests always invoke the Worker, and on the Free plan they receive a 429 once the daily request limit is used up, where an asset-first path would still be served. A pattern prefixed with ! carves an exception out of a broader one.

Serve the 404 page from code

The Worker already knows when a code does not exist. It can return the HTML page itself for clients that ask for HTML, and keep the JSON error for the rest. That needs the assets binding. The finished configuration:

cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };

export default defineConfig(({ mode }) => ({
	worker: {
		name: "shortlinks",
		compatibilityDate: "2026-11-23",
		entrypoint,
		assets: {
			runWorkerFirst: ["/api/*"],
		},
		env: {
			PUBLIC_ORIGIN: bindings.text(
				mode === "production" ? "https://go.example.com" : "http://localhost:8791",
			),
			LIMITS: bindings.json({ codeLength: 6, maxUrlLength: 2048 }),
			ADMIN_TOKEN: bindings.secret(),
			LINKS: bindings.kv(),
			DB: bindings.d1({ name: "shortlinks", id: "8f0c4c3e-52a1-4b7d-9a35-1c2f6d7e8a90" }),
			ASSETS: bindings.assets(),
		},
	},
}));
src/index.ts
@@ -74,7 +74,7 @@
 async function followLink({ request, env, ctx, params }: RouteArgs): Promise<Response> {
 	const code = params.code ?? "";
 	const link = await getLink(env.LINKS, code);
-	if (!link) throw new HttpError(404, "no such link");
+	if (!link) return linkNotFound(request, env);
 
 	const visit = {
 		code,
@@ -88,6 +88,14 @@
 	return Response.redirect(link.url, 302);
 }
 
+async function linkNotFound(request: Request, env: Env): Promise<Response> {
+	const wantsHtml = request.headers.get("Accept")?.includes("text/html") ?? false;
+	if (!wantsHtml) throw new HttpError(404, "no such link");
+
+	const page = await env.ASSETS.fetch(new URL("/404", request.url));
+	return new Response(page.body, { status: 404, headers: page.headers });
+}
+
 function parseTarget(value: unknown, maxLength: number): URL {
 	if (typeof value !== "string" || !URL.canParse(value)) {
 		throw new HttpError(400, "url must be an absolute URL");

env.ASSETS.fetch() returns the asset for a URL as the platform would serve it. Only the path of the URL is used. The page comes back with status 200, so linkNotFound copies its body and headers into a new response with the right status. The assets binding reference covers the options.

Rebuild and restart the preview one last time:

curl -i http://localhost:8794/nope12
HTTP/1.1 404 Not Found
...
content-type: application/json
...

{"error":"no such link"}
curl -i -H 'Accept: text/html' http://localhost:8794/nope12
HTTP/1.1 404 Not Found
...
content-length: 244
content-type: text/html; charset=utf-8
...

A browser navigation to a code that exists is redirected as before:

curl -i -H 'Sec-Fetch-Mode: navigate' -H 'Accept: text/html' http://localhost:8794/snw8zr
HTTP/1.1 302 Found
...
location: https://developers.cloudflare.com/workers/static-assets/
...

Stop the preview. pnpm test and pnpm check pass. The test sends no Accept header, so it takes the JSON branch. Lesson 8 replaces that single test with a suite and takes the project to production.

Exercises

  1. Add public/robots.txt that disallows /api/. In the preview, curl -i http://localhost:8794/robots.txt should show a 200 with content-type: text/plain; charset=utf-8, and a console.log placed at the top of fetch should not fire for it.
  2. Add public/stats.html, a page that reads code from its query string, calls GET /api/links/<code> and shows the target URL and visit count. The result is correct when http://localhost:8791/stats?code=<code> displays the numbers, and in the preview curl -i 'http://localhost:8794/stats.html?code=<code>' answers 307 with location: /stats?code=<code>.
  3. Predict what htmlHandling: "none" changes, then try it in the preview. With that setting /index.html and /404.html should return 200, while / and /404 reach the Worker and return its JSON 404. Decide which behavior you would ship and remove the setting if it is not this one.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are