> ## Documentation Index
> Fetch the complete documentation index at: https://developers.telnyx.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Response Caching

> Cache expensive upstream API responses at the edge with Telnyx KV and a short server-side TTL.

Cache expensive upstream responses for a few minutes. This uses the [KV binding](/docs/edge-compute/kv/quick-start#path-a-the-function-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.

```ts theme={null}
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" } });
}
```

<Note>
  Non-TypeScript functions get the same behavior with the `ttl_secs` REST parameter on the `kvPut` [REST helper](/docs/edge-compute/kv/quick-start#path-b-the-rest-api). If you need to inspect *when* an entry expires, use the application-level envelope instead — see [Key Expiration](/docs/edge-compute/kv/ttl-and-metadata).
</Note>
