@cloudflare/kv-asset-handler package provides utilities for serving static assets from Workers KV, commonly used with Workers Sites.
Installation
Core Functions
getAssetFromKV()
Fetch and serve a static asset from KV storage.
object
required
Event-like object with request and waitUntil
Partial<Options>
Configuration options
Promise<Response>
HTTP response with the asset content
- Throws
NotFoundErrorif asset doesn’t exist - Throws
MethodNotAllowedErrorfor non-GET/HEAD requests - Throws
InternalErrorfor KV namespace issues
mapRequestToAsset()
Map a request URL to an asset path in KV.
Request
required
Original request
Partial<Options>
Asset handler options
Request
Modified request with mapped asset path
- Appends
defaultDocumentto directory paths (e.g.,/about/→/about/index.html) - Adds
defaultDocumentto paths without extensions (e.g.,/about→/about/index.html) - Preserves paths with file extensions as-is
serveSinglePageApp()
Serve a single-page application (SPA), returning index.html for all HTML requests.
Request
required
Original request
Partial<Options>
Asset handler options
Request
Modified request, mapping HTML requests to root index.html
- Static assets (JS, CSS, images) are served normally
- Requests for HTML files return the root
index.html - Perfect for client-side routing in React, Vue, etc.
Error Classes
NotFoundError
Thrown when an asset is not found in KV.
number
default:"404"
HTTP status code
string
Error message
MethodNotAllowedError
Thrown for unsupported HTTP methods.
number
default:"405"
HTTP status code
InternalError
Thrown for internal KV or configuration errors.
number
default:"500"
HTTP status code