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.
1. Create a KV namespace
Section titled “1. Create a KV namespace”wrangler kv namespace create SESSIONS2. Add to wrangler.toml
Section titled “2. Add to wrangler.toml”[[kv_namespaces]]binding = "SESSIONS"id = "your-kv-id"3. Use in your app
Section titled “3. Use in your app”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.
What it stores
Section titled “What it stores”| Key pattern | Value | TTL | Purpose |
|---|---|---|---|
session:{id} | User ID | Session duration (default 30 days) | Fast session validation without hitting D1 |
magic:{token} | Email address | Link expiry (default 10 min) | Magic link token storage |
oauth:{state} | State metadata | 10 min | OAuth 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.
CacheAdapter interface
Section titled “CacheAdapter interface”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>;}Writing a custom adapter
Section titled “Writing a custom adapter”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), // ...});