Introduction
For use cases requiring low latency even with serverless — distribute processing to the edge with Cloudflare Workers and Vercel Edge Runtime for sub-10ms responses globally. Let Claude Code design this.
CLAUDE.md Rules
## Edge Function Rules
- Use cases: auth check, rate limiting, A/B test, geo-routing
- Max CPU time: 50ms
- Memory: < 128MB
- No filesystem (use KV/D1/R2)
- No Node.js modules (Web API only)
Generated Implementation
// JWT verification at edge (Web Crypto API)
async function verifyJWT(token: string, secret: string) {
const [headerB64, payloadB64, signatureB64] = token.split('.');
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify']
);
const valid = await crypto.subtle.verify(
'HMAC', key, decodeBase64(signatureB64),
new TextEncoder().encode(`${headerB64}.${payloadB64}`)
);
if (!valid) return null;
return JSON.parse(atob(payloadB64));
}
// Rate limiting with KV
async function checkRateLimit(request: Request, env: Env) {
const ip = request.headers.get('CF-Connecting-IP') ?? 'unknown';
const key = `ratelimit:${ip}:${Math.floor(Date.now() / 60_000)}`;
const count = parseInt(await env.RATE_LIMIT_KV.get(key) ?? '0');
if (count >= 100) return { allowed: false, retryAfterSeconds: 60 };
await env.RATE_LIMIT_KV.put(key, String(count + 1), { expirationTtl: 90 });
return { allowed: true };
}
// A/B test with sticky cookies
async function abTest(request: Request) {
const cookies = parseCookies(request.headers.get('Cookie') ?? '');
let variant = cookies['ab_checkout'];
if (!variant) {
const hash = await hashString(userId + 'checkout_v2');
variant = hash[0] < 128 ? 'control' : 'treatment';
}
const response = await fetch(variant === 'treatment' ? '/checkout-v2' : '/checkout', request);
if (!cookies['ab_checkout']) {
response.headers.append('Set-Cookie', `ab_checkout=${variant}; Max-Age=604800`);
}
return response;
}
Summary
- JWT at edge: reduces origin auth overhead using Web Crypto API
- Rate limiting with KV: DDoS never reaches origin
- A/B test: sticky cookie with deterministic hashing
- Cache API: edge caches GET responses with s-maxage
Review with **Code Review Pack (980 yen)* at prompt-works.jp*
myouga (@myougatheaxo) — Axolotl VTuber.
Top comments (0)