Skip to main content
Patterns for using KV in your edge functions.

Session Storage with TTL

Store user sessions at the edge with automatic expiration:
const SESSION_TTL = 86400; // 24 hours

async function handler(request) {
    const sessionId = request.headers.get("X-Session-ID");
    
    // Get session
    let session = await kvGet(`session:${sessionId}`);
    
    if (!session) {
        session = JSON.stringify({ created: Date.now(), views: 0 });
    } else {
        const data = JSON.parse(session);
        data.views++;
        session = JSON.stringify(data);
    }
    
    // Update session with TTL (auto-expires in 24h)
    await kvPutWithTTL(`session:${sessionId}`, session, SESSION_TTL);
    
    return new Response(session);
}

// Helper: PUT with TTL
async function kvPutWithTTL(key, value, ttl) {
    const response = await fetch(
        `https://api.telnyx.com/v2/storage/kvs/${KV_NAMESPACE_ID}/keys/${encodeURIComponent(key)}`,
        {
            method: "PUT",
            headers: {
                "Authorization": `Bearer ${API_KEY}`,
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ 
                value: toBase64(value),
                expiration_ttl: ttl
            })
        }
    );
    if (!response.ok) {
        throw new Error(`KV write error: ${response.status}`);
    }
}

API Response Caching with TTL

Cache expensive API responses with automatic expiration:
const CACHE_TTL = 300; // 5 minutes

async function handler(request) {
    const cacheKey = `api:${new URL(request.url).pathname}`;
    
    // Check cache
    const cached = await kvGet(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 5-minute TTL
    await kvPutWithTTL(cacheKey, data, CACHE_TTL);
    
    return new Response(data, {
        headers: { "X-Cache": "MISS" }
    });
}

Feature Flags

Store and retrieve feature flags:
async function handler(request) {
    const newUIEnabled = await kvGet("feature:new-ui");
    
    if (newUIEnabled === "true") {
        return serveNewUI(request);
    }
    
    return serveOldUI(request);
}