Use Cases

Cloudflare Workers with Claude Code

Learn about Cloudflare Workers using Claude Code. Practical tips and code examples included.

Accelerating Cloudflare Workers Development With Claude Code

Cloudflare Workers is a serverless platform that runs JavaScript/TypeScript on Cloudflare’s global network. Built on the V8 engine, it achieves zero cold starts and blazing-fast responses. With Claude Code, you can efficiently work with Workers-specific APIs and bindings.

Starting a Project

> Create a Cloudflare Workers project.
> Use the Hono framework and a D1 database.
npm create cloudflare@latest my-worker -- --template=hello-world
cd my-worker
npm install hono
# wrangler.toml
name = "my-api"
main = "src/index.ts"
compatibility_date = "2024-12-01"

[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

[[kv_namespaces]]
binding = "CACHE"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

[[r2_buckets]]
binding = "STORAGE"
bucket_name = "my-bucket"

Implementing an API With Hono

> Build a CRUD API with the Hono framework.
> Also integrate with a D1 database.
// src/index.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { jwt } from 'hono/jwt';

type Bindings = {
  DB: D1Database;
  CACHE: KVNamespace;
  STORAGE: R2Bucket;
  JWT_SECRET: string;
};

const app = new Hono<{ Bindings: Bindings }>();

app.use('/api/*', cors());

// List posts
app.get('/api/posts', async (c) => {
  const { results } = await c.env.DB.prepare(
    'SELECT * FROM posts ORDER BY created_at DESC LIMIT 20'
  ).all();

  return c.json({ posts: results });
});

// Create a post
app.post('/api/posts', async (c) => {
  const { title, content } = await c.req.json();

  const result = await c.env.DB.prepare(
    'INSERT INTO posts (title, content, created_at) VALUES (?, ?, datetime())'
  )
    .bind(title, content)
    .run();

  // Clear the cache
  await c.env.CACHE.delete('posts:latest');

  return c.json({ id: result.meta.last_row_id }, 201);
});

// Image upload (R2)
app.post('/api/upload', async (c) => {
  const formData = await c.req.formData();
  const file = formData.get('file') as File;

  if (!file) {
    return c.json({ error: 'File required' }, 400);
  }

  const key = `uploads/${Date.now()}-${file.name}`;
  await c.env.STORAGE.put(key, file.stream(), {
    httpMetadata: { contentType: file.type },
  });

  return c.json({ key, url: `/api/files/${key}` });
});

export default app;

D1 Database Migrations

-- migrations/0001_create_tables.sql
CREATE TABLE IF NOT EXISTS posts (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  content TEXT NOT NULL,
  slug TEXT UNIQUE,
  published BOOLEAN DEFAULT FALSE,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_posts_slug ON posts(slug);
CREATE INDEX idx_posts_published ON posts(published, created_at);
# Run migrations
npx wrangler d1 migrations apply my-database

# Local development
npx wrangler d1 migrations apply my-database --local
npx wrangler dev

Using KV for Caching

// src/cache.ts
export async function getCachedData<T>(
  kv: KVNamespace,
  key: string,
  fetcher: () => Promise<T>,
  ttl = 3600
): Promise<T> {
  const cached = await kv.get(key, 'json');
  if (cached) return cached as T;

  const data = await fetcher();
  await kv.put(key, JSON.stringify(data), { expirationTtl: ttl });
  return data;
}

// Usage example
app.get('/api/stats', async (c) => {
  const stats = await getCachedData(
    c.env.CACHE,
    'stats:daily',
    async () => {
      const { results } = await c.env.DB.prepare(
        'SELECT COUNT(*) as count FROM posts WHERE published = TRUE'
      ).all();
      return results[0];
    },
    300 // cache for 5 minutes
  );

  return c.json(stats);
});

Deployment and Monitoring

# Deploy
npx wrangler deploy

# View logs
npx wrangler tail

# Set secrets
npx wrangler secret put JWT_SECRET

Summary

Combining Cloudflare Workers’ rich set of bindings with Claude Code lets you efficiently build full-stack APIs that run at the edge. See the serverless functions guide and introduction to edge computing for more.

For more on Cloudflare Workers, see the official Cloudflare Workers documentation.

#Claude Code #Cloudflare Workers #edge computing #serverless #API

Level up your Claude Code workflow

50 battle-tested prompt templates you can copy-paste into Claude Code right now.

Free

Free PDF: Claude Code Cheatsheet in 5 Minutes

Key commands, shortcuts, and prompt examples on a single printable page.

Download PDF
M

About the Author

Masa

Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.