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.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 Deployment Checks Before You Publish a Multilingual Claude Code Article Every Day
A practical checklist for publishing daily multilingual Claude Code articles without missing locales, breaking CTAs, or shipping stale pages.
Codex Automations for Content Ops: A Daily Revenue Workflow for Claude Code Sites
Use Codex Automations to turn analytics, article updates, CTA improvements, deployment, and verification into a daily revenue workflow.
Claude Code × GCP Cloud Functions Complete Guide | Rapid Serverless Function Development
Streamline GCP Cloud Functions with Claude Code. Implement HTTP/Pub/Sub/Firestore triggers, local testing, and deployment automation with real-world code examples from Masa's experience.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.