What is @cloudflare/kv-asset-handler?
@cloudflare/kv-asset-handler is a package designed to help developers serve static assets from Cloudflare Workers using Cloudflare's KV (Key-Value) storage. It simplifies the process of handling requests for static assets, such as HTML, CSS, JavaScript, and images, by providing a straightforward API to fetch and serve these assets efficiently.
What are @cloudflare/kv-asset-handler's main functionalities?
Serve Static Assets
This feature allows you to serve static assets stored in Cloudflare's KV storage. The code sample demonstrates how to use the `getAssetFromKV` function to handle fetch events and return the requested asset.
const { getAssetFromKV } = require('@cloudflare/kv-asset-handler');
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
try {
const response = await getAssetFromKV(event);
return response;
} catch (e) {
return new Response('Error fetching asset', { status: 500 });
}
}
Custom Cache Control
This feature allows you to customize cache control settings for the assets served. The code sample shows how to set browser and edge TTL (Time To Live) values to control caching behavior.
const { getAssetFromKV, mapRequestToAsset } = require('@cloudflare/kv-asset-handler');
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
try {
const options = {
cacheControl: {
browserTTL: 60 * 60 * 24, // 1 day
edgeTTL: 60 * 60 * 24 * 30, // 30 days
},
};
const response = await getAssetFromKV(event, options);
return response;
} catch (e) {
return new Response('Error fetching asset', { status: 500 });
}
}
Custom Asset Mapping
This feature allows you to customize how requests are mapped to assets in KV storage. The code sample demonstrates how to modify the request URL to remove a '/static' prefix before fetching the asset.
const { getAssetFromKV, mapRequestToAsset } = require('@cloudflare/kv-asset-handler');
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
try {
const customKeyModifier = request => {
let url = new URL(request.url);
url.pathname = url.pathname.replace('/static', '');
return new Request(url.toString(), request);
};
const response = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier });
return response;
} catch (e) {
return new Response('Error fetching asset', { status: 500 });
}
}
Other packages similar to @cloudflare/kv-asset-handler
express-static
The `express-static` middleware is used in Express.js applications to serve static files. It is similar to @cloudflare/kv-asset-handler in that it helps serve static assets, but it is designed for use with Express.js and does not integrate with Cloudflare Workers or KV storage.
serve-static
The `serve-static` package is a standalone middleware for serving static files. It is often used with Node.js servers and frameworks like Express. Unlike @cloudflare/kv-asset-handler, it does not provide integration with Cloudflare Workers or KV storage.
static-server
The `static-server` package is a simple, zero-configuration command-line HTTP server for serving static files. It is useful for local development and testing but does not offer the same level of integration with Cloudflare Workers or KV storage as @cloudflare/kv-asset-handler.
@cloudflare/kv-asset-handler
Installation
Add this package to your package.json
by running this in the root of your
project's directory:
npm i @cloudflare/kv-asset-handler
Usage
Currently this exports a single function getAssetFromKV
that maps Request
objects to KV Assets, and throws an Error
if it cannot.
import { getAssetFromKV } from '@cloudflare/kv-asset-handler'
getAssetFromKV
is a function that takes a Request
object and returns a Response
object if the request matches an asset in KV, otherwise it will throw an Error
.
Note this package was designed to work with Worker Sites. If you are not using Sites make sure to call the bucket you are serving assets from __STATIC_CONTENT
Example
This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from /
.
import { getAssetFromKV } from '@cloudflare/kv-asset-handler'
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.url.includes('/docs')) {
try {
return await getAssetFromKV(request, url => {
if (url.endsWith('/')) url += 'index.html'
return url.replace('/docs', '')
})
} catch (e) {
return new Response(`"${customKeyModifier(request.url)}" not found`, {
status: 404,
statusText: 'not found',
})
}
} else return fetch(request)
}