Skip to main content
Patterns for using KV in your edge functions. These examples build on the raw kvGet/kvPut helpers from the Quick Start and the kvGetWithExpiry/kvPutWithExpiry helpers from Key expiration (KV has no native TTL, so expiry is enforced in your code).

Session Storage with Expiry

Store user sessions at the edge with an application-level expiry:
const SESSION_TTL = 86400; // 24 hours

async function handler(request) {
    const sessionId = request.headers.get("X-Session-ID");

    // Read session (null if missing or expired)
    let session = await kvGetWithExpiry(`session/${sessionId}`);

    if (!session) {
        session = JSON.stringify({ created: Date.now(), views: 0 });
    } else {
        const data = JSON.parse(session);
        data.views++;
        session = JSON.stringify(data);
    }

    // Store with a 24h expiry
    await kvPutWithExpiry(`session/${sessionId}`, session, SESSION_TTL);

    return new Response(session);
}

API Response Caching with Expiry

Cache expensive API responses with an application-level expiry:
const CACHE_TTL = 300; // 5 minutes

async function handler(request) {
    const cacheKey = `cache/api${new URL(request.url).pathname}`;

    // Check cache
    const cached = await kvGetWithExpiry(cacheKey);
    if (cached) {
        return new Response(cached, {
            headers: { "X-Cache": "HIT" }
        });
    }

    // Fetch from origin
    const response = await fetch("https://api.example.com/data");
    const data = await response.text();

    // Cache with a 5-minute expiry
    await kvPutWithExpiry(cacheKey, data, CACHE_TTL);

    return new Response(data, {
        headers: { "X-Cache": "MISS" }
    });
}

Feature Flags

Store and retrieve feature flags (no expiry needed):
async function handler(request) {
    const newUIEnabled = await kvGet("flag/new-ui");

    if (newUIEnabled === "true") {
        return serveNewUI(request);
    }

    return serveOldUI(request);
}