← Cloudflare Workers / workers / static-assets / routing
Worker skript
Pokud máte nakonfigurované statické assets i skript Workeru, Cloudflare se nejprve pokusí obsloužit statické assets, pokud některý odpovídá příchozímu požadavku. Více o tom, jak assets přiřazujeme, najdete v Dokumentace ke zpracování HTML.
Pokud se nenajde odpovídající statické aktivum, Cloudflare spustí váš skript Workeru.
To vám umožňuje snadno kombinovat tyto dvě funkce a vytvářet výkonné aplikace (např. full-stack aplikace, nebo Jednostránková aplikace (SPA) nebo Aplikace s generováním statických stránek (SSG) s API).
Kontext Cloudflare Access
Nejprve spusťte skript svého Workeru
Můžete nakonfigurovat assets.run_worker_first nastavení pro řízení toho, kdy se skript Workeru spouští ve vztahu k obsluze statických assetů. Díky tomu máte větší kontrolu nad tím, jak a kdy jsou tyto assety obsluhovány, a lze to použít k implementaci "middlewaru" pro požadavky.
Spustit Worker před každým požadavkem
Pokud potřebujete, aby se skript Workeru vždy spustil ještě před doručením statických souborů (například chcete zaznamenávat požadavky, provádět ověřovací kontroly, použít HTMLRewriter, nebo jinak transformovat assety před jejich odesláním), nastavte run_worker_first na true:
{
"name": "my-worker",
// Set this to today's date
"compatibility_date": "2026-08-28",
"main": "./worker/index.ts",
"assets": {
"directory": "./dist/",
"binding": "ASSETS",
"run_worker_first": true
}
}name = "my-worker"
# Set this to today's date
compatibility_date = "2026-08-28"
main = "./worker/index.ts"
[assets]
directory = "./dist/"
binding = "ASSETS"
run_worker_first = trueimport { WorkerEntrypoint } from "cloudflare:workers";
export default class extends WorkerEntrypoint {
async fetch(request) {
// You can perform checks before fetching assets
const user = await checkIfRequestIsAuthenticated(request);
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
// You can then just fetch the assets as normal, or you could pass in a custom Request object here if you wanted to fetch some other specific asset
const assetResponse = await this.env.ASSETS.fetch(request);
// You can return static asset response as-is, or you can transform them with something like HTMLRewriter
return new HTMLRewriter()
.on("#user", {
element(element) {
element.setInnerContent(JSON.stringify({ name: user.name }));
},
})
.transform(assetResponse);
}
}import { WorkerEntrypoint } from "cloudflare:workers";
export default class extends WorkerEntrypoint<Env> {
async fetch(request: Request) {
// You can perform checks before fetching assets
const user = await checkIfRequestIsAuthenticated(request);
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
// You can then just fetch the assets as normal, or you could pass in a custom Request object here if you wanted to fetch some other specific asset
const assetResponse = await this.env.ASSETS.fetch(request);
// You can return static asset response as-is, or you can transform them with something like HTMLRewriter
return new HTMLRewriter()
.on("#user", {
element(element) {
element.setInnerContent(JSON.stringify({ name: user.name }));
},
})
.transform(assetResponse);
}
}Spustit Worker jako první pro vybrané cesty
Selektivní směrování s prioritou Workeru můžete také nakonfigurovat pomocí pole vzorů tras, často v kombinaci s single-page-application nastavení. Díky tomu můžete Worker spustit jako první pouze pro konkrétní routy, zatímco ostatní požadavky se budou řídit výchozím chováním asset first:
{
"name": "my-worker",
// Set this to today's date
"compatibility_date": "2026-08-28",
"main": "./worker/index.ts",
"assets": {
"directory": "./dist/",
"not_found_handling": "single-page-application",
"binding": "ASSETS",
"run_worker_first": ["/oauth/callback"]
}
}name = "my-worker"
# Set this to today's date
compatibility_date = "2026-08-28"
main = "./worker/index.ts"
[assets]
directory = "./dist/"
not_found_handling = "single-page-application"
binding = "ASSETS"
run_worker_first = [ "/oauth/callback" ]import { WorkerEntrypoint } from "cloudflare:workers";
export default class extends WorkerEntrypoint {
async fetch(request) {
// The only thing this Worker script does is handle an OAuth callback.
// All other requests either serve an asset that matches or serve the index.html fallback, without ever hitting this code.
const url = new URL(request.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const accessToken = await exchangeCodeForToken(code, state);
const sessionIdentifier = await storeTokenAndGenerateSession(accessToken);
// Redirect back to the index, but set a cookie that the front-end will use.
return new Response(null, {
headers: {
Location: "/",
"Set-Cookie": `session_token=${sessionIdentifier}; HttpOnly; Secure; SameSite=Lax; Path=/`,
},
});
}
}import { WorkerEntrypoint } from "cloudflare:workers";
export default class extends WorkerEntrypoint<Env> {
async fetch(request: Request) {
// The only thing this Worker script does is handle an OAuth callback.
// All other requests either serve an asset that matches or serve the index.html fallback, without ever hitting this code.
const url = new URL(request.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const accessToken = await exchangeCodeForToken(code, state);
const sessionIdentifier = await storeTokenAndGenerateSession(accessToken);
// Redirect back to the index, but set a cookie that the front-end will use.
return new Response(null, {
headers: {
Location: "/",
"Set-Cookie": `session_token=${sessionIdentifier}; HttpOnly; Secure; SameSite=Lax; Path=/`,
},
});
}
}