Start from worker
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. To do so, follow these instructions:
- Create a directory in the root of your project (for example,
workers-site
) and add configuration to yourwrangler.toml
file to point to it. Add the path to your Worker script (probablyindex.js
).
---
filename: 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 invoke it within your function handler 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
refer to
the template’s source.
- Run
preview
orpublish
as you would normally with your Worker project.
$ wrangler publish