Skip to main content
Cache expensive upstream responses for a few minutes. This uses the KV binding (bound as MY_KV) with a server-side TTL: pass expirationTtl on the write and KV deletes the key automatically once it elapses — no cleanup code. Requires @telnyx/edge-runtime ≥ 0.2.2.
import { env } from "@telnyx/edge-runtime";

const CACHE_TTL = 300; // 5 minutes

export async function handler(request: Request): Promise<Response> {
    const cacheKey = `cache/api${new URL(request.url).pathname}`;

    // null once the TTL has elapsed (or if never cached)
    const cached = await env.MY_KV.get(cacheKey);
    if (cached !== null) {
        return new Response(cached, { headers: { "X-Cache": "HIT" } });
    }

    const upstream = await fetch("https://api.example.com/data");
    const data = await upstream.text();

    await env.MY_KV.put(cacheKey, data, { expirationTtl: CACHE_TTL });

    return new Response(data, { headers: { "X-Cache": "MISS" } });
}
Non-TypeScript functions get the same behavior with the ttl_secs parameter on a REST API write. If you need to inspect when an entry expires, use the application-level envelope instead — see Key Expiration.