Using KV
Session storage, caching, and rate limiting with Cloudflare KV
Cloudflare KV is used by the Quickback Stack for session storage, caching, and rate limiting.
Session Storage
Better Auth stores sessions in KV by default for fast edge-based lookups. This is auto-configured by the compiler — no setup needed.
// How sessions work internally (auto-generated)
// On login: session stored in KV
await kv.put(`session:${sessionToken}`, JSON.stringify(sessionData), {
expirationTtl: 60 * 60 * 24 * 7, // 7 days
});
// On each request: session retrieved from KV
const session = await kv.get(`session:${sessionToken}`, "json");Sessions are automatically:
- Created on sign-in (email/password, passkey, magic link, etc.)
- Validated on every authenticated request via the
Authorization: Bearer <token>header - Expired after the configured TTL (default: 7 days)
- Deleted on sign-out
Rate Limiting
KV powers the rate limiting middleware that protects auth endpoints:
// Rate limit key structure (auto-generated)
// Key: ratelimit:{ip}:{endpoint}
// Value: request count
// TTL: rate limit window (e.g., 60 seconds)
const key = `ratelimit:${ip}:${endpoint}`;
const count = await kv.get(key);
if (count && parseInt(count) > limit) {
return c.json({ error: "Too many requests" }, 429);
}See Auth Security for rate limiting configuration options.
Caching
You can use KV in custom action handlers for caching frequently accessed data:
// In an action handler
execute: async ({ db, ctx }) => {
const kv = ctx.env.KV;
// Check cache first
const cached = await kv.get("expensive-query-result", "json");
if (cached) return cached;
// Compute and cache
const result = await db.select().from(analytics);
await kv.put("expensive-query-result", JSON.stringify(result), {
expirationTtl: 300, // 5 minutes
});
return result;
}See Also
- KV Setup — Namespace creation and wrangler bindings
- Auth Security — Rate limiting and cookie security configuration