Workers Sites require Wrangler ↗ — make sure to use the latest version.
If you have a pre-existing Worker project, you can use Workers Sites to serve static assets to the Worker.
-
Create a directory that will contain the assets in the root of your project (for example,
./public) -
Add configuration to your Wrangler file to point to it.
{ "site": { "bucket": "./public" // Add the directory with your static assets! } }[site] bucket = "./public" -
Install the
@cloudflare/kv-asset-handlerpackage in your project:npm i -D @cloudflare/kv-asset-handler -
Import the
getAssetFromKV()function into your Worker entry point and use it to respond with static assets.
import { getAssetFromKV } from "@cloudflare/kv-asset-handler";
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
const assetManifest = JSON.parse(manifestJSON);
export default {
async fetch(request, env, ctx) {
try {
// Add logic to decide whether to serve an asset or run your original Worker code
return await getAssetFromKV(
{
request,
waitUntil: ctx.waitUntil.bind(ctx),
},
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
},
);
} catch (e) {
let pathname = new URL(request.url).pathname;
return new Response(`"${pathname}" not found`, {
status: 404,
statusText: "not found",
});
}
},
};import { getAssetFromKV } from "@cloudflare/kv-asset-handler";
addEventListener("fetch", (event) => {
event.respondWith(handleEvent(event));
});
async function handleEvent(event) {
try {
// Add logic to decide whether to serve an asset or run your original Worker code
return await getAssetFromKV(event);
} catch (e) {
let pathname = new URL(event.request.url).pathname;
return new Response(`"${pathname}" not found`, {
status: 404,
statusText: "not found",
});
}
}For more information on the configurable options of getAssetFromKV() refer to kv-asset-handler docs ↗.
-
Run
wrangler deployornpx wrangler deployas you would normally with your Worker project. Wrangler will automatically upload the assets found in the configured directory.npx wrangler deploy