typescriptintermediate

Cloudflare Workers — Edge API in TypeScript

Build serverless edge APIs with Cloudflare Workers, KV storage, and request routing.

typescript
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.