Skip to main content
The @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
Errors:
  • Throws NotFoundError if asset doesn’t exist
  • Throws MethodNotAllowedError for non-GET/HEAD requests
  • Throws InternalError for 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
Behavior:
  • Appends defaultDocument to directory paths (e.g., /about/ → /about/index.html)
  • Adds defaultDocument to 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
Behavior:
  • 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

Usage Examples

Basic Static Site

Custom Cache Control

Dynamic Cache Control

Single Page Application

API + Static Assets

Custom 404 Page

With Custom Headers


Type Definitions