Skip to content

KV Adapter

Workers Auth uses Cloudflare Workers KV for fast session caching and temporary token storage. The KV adapter handles magic link tokens, OAuth state parameters, and session lookups at the edge.

Terminal window
wrangler kv namespace create SESSIONS
[[kv_namespaces]]
binding = "SESSIONS"
id = "your-kv-id"
import { KVAdapter } from 'workers-auth/adapters/kv';
const auth = WorkersAuth({
cache: (binding) => KVAdapter(binding),
// ...
});

The cache config takes a factory function. At request time, Workers Auth passes the SESSIONS binding from your Worker’s env object.

Key patternValueTTLPurpose
session:{id}User IDSession duration (default 30 days)Fast session validation without hitting D1
magic:{token}Email addressLink expiry (default 10 min)Magic link token storage
oauth:{state}State metadata10 minOAuth CSRF state parameter

Session validation checks KV first (fast path) and falls back to D1 on a cache miss. On a D1 hit, the session is re-cached in KV.

The KV adapter implements the CacheAdapter interface:

interface CacheAdapter {
get(key: string): Promise<string | null>;
set(key: string, value: string, ttl?: number): Promise<void>;
delete(key: string): Promise<void>;
}

To use a different cache backend (Redis, Durable Objects, in-memory), implement CacheAdapter:

import type { CacheAdapter } from 'workers-auth';
function MyCustomCache(binding: any): CacheAdapter {
return {
async get(key) {
// Return string value or null
},
async set(key, value, ttl) {
// Store value with optional TTL in seconds
},
async delete(key) {
// Remove key
},
};
}

Then pass it to WorkersAuth:

const auth = WorkersAuth({
cache: (binding) => MyCustomCache(binding),
// ...
});