Cloudflare Workers mit Claude Code
Erfahren Sie, wie Sie Cloudflare Workers mit Claude Code verwenden. Mit praktischen Tipps und Codebeispielen.
Cloudflare Workers-Entwicklung mit Claude Code beschleunigen
Cloudflare Workers ist eine serverlose Plattform, die JavaScript/TypeScript auf dem globalen Netzwerk von Cloudflare ausführt. Basierend auf der V8-Engine bietet sie schnelle Antwortzeiten ohne Cold Start. Mit Claude Code können Sie auch Workers-spezifische APIs und Bindings effizient nutzen.
Projekt starten
> Erstelle ein Cloudflare Workers-Projekt.
> Mit Hono-Framework und D1-Datenbank.
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"
API-Implementierung mit Hono
> Erstelle eine CRUD-API mit dem Hono-Framework.
> Implementiere auch die Anbindung an die D1-Datenbank.
// 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());
// Artikelliste
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 });
});
// Artikel erstellen
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();
// Cache leeren
await c.env.CACHE.delete('posts:latest');
return c.json({ id: result.meta.last_row_id }, 201);
});
// Bild-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-Datenbank-Migration
-- 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);
# Migration ausführen
npx wrangler d1 migrations apply my-database
# Lokale Entwicklung
npx wrangler d1 migrations apply my-database --local
npx wrangler dev
KV-Cache nutzen
// 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;
}
// Verwendungsbeispiel
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 // 5 Minuten Cache
);
return c.json(stats);
});
Deployment und Monitoring
# Deployment
npx wrangler deploy
# Logs überprüfen
npx wrangler tail
# Secrets konfigurieren
npx wrangler secret put JWT_SECRET
Zusammenfassung
Die Kombination der umfangreichen Bindings von Cloudflare Workers mit Claude Code ermöglicht den effizienten Aufbau von Full-Stack-APIs am Edge. Siehe auch den Leitfaden zu serverlosen Funktionen und die Einführung in Edge Computing.
Details zu Cloudflare Workers finden Sie in der offiziellen Cloudflare Workers-Dokumentation.
Related Posts
So beschleunigen Sie Ihre Nebenprojekte mit Claude Code [Mit Beispielen]
Erfahren Sie, wie Sie persönliche Entwicklungsprojekte mit Claude Code drastisch beschleunigen. Inklusive realer Beispiele und eines praktischen Workflows von der Idee bis zum Deployment.
So automatisieren Sie Refactoring mit Claude Code
Erfahren Sie, wie Sie Code-Refactoring mit Claude Code effizient automatisieren. Inklusive praktischer Prompts und konkreter Refactoring-Muster für reale Projekte.
Vollständiger CORS-Konfigurationsleitfaden mit Claude Code
Erfahren Sie alles über die CORS-Konfiguration mit Claude Code. Mit praktischen Tipps und Codebeispielen.