Skip to main content
Store user sessions at the edge and expire them after a day. This uses the KV binding (bound as MY_KV) with a server-side TTL: pass expirationTtl on the write and KV deletes the session automatically once it elapses. Each write renews the TTL, so an active session slides forward and an abandoned one expires. Requires @telnyx/edge-runtime ≥ 0.2.2.
import { env } from "@telnyx/edge-runtime";

const SESSION_TTL = 86_400; // 24 hours

interface Session {
    created: number;
    views: number;
}

export async function handler(request: Request): Promise<Response> {
    const sessionId = request.headers.get("X-Session-ID");
    if (!sessionId) {
        return new Response("Missing X-Session-ID", { status: 400 });
    }
    const key = `session/${sessionId}`;

    // Read session (null if missing or expired)
    const existing = await env.MY_KV.get<Session>(key, { type: "json" });
    const data = existing
        ? { ...existing, views: existing.views + 1 }
        : { created: Date.now(), views: 0 };

    // Store with a 24h server-side TTL — renewed on every write
    await env.MY_KV.put(key, JSON.stringify(data), { expirationTtl: SESSION_TTL });

    return new Response(JSON.stringify(data), {
        headers: { "Content-Type": "application/json" },
    });
}
Non-TypeScript functions get the same behavior with the ttl_secs parameter on a REST API write. If you need to inspect when a session expires, use the application-level envelope instead — see Key Expiration.