worker: fix assets binding and SPA routes

This commit is contained in:
every.channel 2026-02-16 17:46:32 -05:00
parent 339aef50e0
commit 2e5fb0880f
No known key found for this signature in database
9 changed files with 510 additions and 11 deletions

View file

@ -115,17 +115,28 @@ export default {
}
// Serve static assets from the Worker Assets binding.
// SPA fallback: unknown paths serve the app shell (`/index.html`).
// SPA routing: serve the app shell for "route-like" paths (e.g. `/watch`).
//
// Cloudflare's Assets binding may otherwise issue a redirect for unknown paths (e.g. `/watch` -> `/`),
// which breaks stable share links.
const assets = (env as unknown as { ASSETS?: Fetcher }).ASSETS;
if (!assets || typeof (assets as any).fetch !== "function") {
return new Response("Assets binding not configured", { status: 500 });
}
const res = await assets.fetch(request);
if (res.status !== 404) return res;
const method = request.method.toUpperCase();
const is_nav = method === "GET" || method === "HEAD";
const is_likely_asset = url.pathname.includes(".");
url.pathname = "/index.html";
return assets.fetch(new Request(url.toString(), request));
// Use `/` as the app shell. Some asset handlers redirect `/index.html` -> `/`,
// which turns SPA routes into 307s instead of serving the HTML.
if (is_nav && !is_likely_asset && url.pathname !== "/") {
const u = new URL(request.url);
u.pathname = "/";
return assets.fetch(new Request(u.toString(), request));
}
return assets.fetch(request);
},
};