Cloudflare Workers — Edge API in TypeScript
Build serverless edge APIs with Cloudflare Workers, KV storage, and request routing.
export interface Env {
KV_STORE: KVNamespace;
API_SECRET: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// Simple router
if (url.pathname === '/api/health') {
return Response.json({ status: 'ok', edge: request.cf?.colo });
}
if (url.pathname.startsWith('/api/kv/')) {
const key = url.pathname.replace('/api/kv/', '');
if (request.method === 'GET') {
const value = await env.KV_STORE.get(key);
if (!value) return new Response('Not found', { status: 404 });
return Response.json(JSON.parse(value));
}
if (request.method === 'PUT') {
const auth = request.headers.get('Authorization');
if (auth !== `Bearer ${env.API_SECRET}`) {
return new Response('Unauthorized', { status: 401 });
}
const body = await request.text();
await env.KV_STORE.put(key, body, { expirationTtl: 86400 });
return Response.json({ stored: key });
}
}
return new Response('Not found', { status: 404 });
},
};Sponsored
Cloudflare R2
Use Cases
- Low-latency edge APIs without origin servers
- KV-backed feature flags and configuration
- Edge-based URL shortener or redirect service
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
GitHub Actions — Deploy to Cloudflare Pages
Automated deployment pipeline to Cloudflare Pages with build preview for PRs and production on main.
Best for: Zero-config deployment for static Next.js exports
AWS SDK v3 — S3 Operations in TypeScript
Perform S3 operations with AWS SDK v3: upload, download, list, presigned URLs, and multipart upload.
Best for: Server-side file uploads to S3
Vercel API — Trigger and List Deployments
Use the Vercel REST API to trigger deployments, list recent builds, and check deployment status.
Best for: Triggering deployments from CI or Slack bots
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
Best for: App startup validation