Start from worker
Workers Sites require Wrangler — make sure to be on the latest version.
Make sure to be on the latest version.
If you have a pre-existing Worker project, you can use Workers Sites to serve static assets to the Worker. To do so, follow these instructions:
Create a directory in the root of your project (e.g.
workers-site
) and add configuration to yourwrangler.toml
to point to it. Also add the path to your Worker script (probablyindex.js
).wrangler.toml
# ... (whatever you already have here) [site]bucket = "./my-dir" # Add the directory with your static assets!entry-point = "./workers-site" # JS folder serving your assets
Add the
@cloudflare/kv-asset-handler
package to your project:$ npm i @cloudflare/kv-asset-handler
Import the package’s code into your Worker script, and use it in the handler you’d like to respond with static assets:
import { getAssetFromKV } from "@cloudflare/kv-asset-handler" addEventListener("fetch", event => { event.respondWith(handleEvent(event))}) async function handleEvent(event) { try { 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
see the template’s source.You should now be all set you can run
preview
orpublish
as you would normally with your Worker project!$ wrangler publish