Cloudflare Workers: Claude Code 활용 가이드
cloudflare workers: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
Cloudflare Workers개발をClaude Code로 가속화하기
Cloudflare Workersは、Cloudflareのグローバル네트워크上でJavaScript/TypeScriptを実行できる서버리스プラット폼です。V8エンジンをベースとし、コールドスタートゼロで高速な응답を実現します。Claude Codeを활용すれば、Workers特有のAPIやバインディングも효율적으로扱えます。
프로젝트の立ち上げ
> Cloudflare Workersの프로젝트를 생성해줘。
> Hono프레임워크とD1데이터베이스를 사용하는구성で。
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"
Hono를 사용한API구현
> Hono프레임워크でCRUD APIを作って。
> D1데이터베이스との연동も구현して。
// 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());
// 글목록
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 });
});
// 글생성
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();
// 캐시の클리어
await c.env.CACHE.delete('posts:latest');
return c.json({ id: result.meta.last_row_id }, 201);
});
// 이미지업로드(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데이터베이스の마이그레이션
-- 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);
# マイグレーションの実行
npx wrangler d1 migrations apply my-database
# ローカル開発
npx wrangler d1 migrations apply my-database --local
npx wrangler dev
KV캐시の활용
// 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 // 5分캐시
);
return c.json(stats);
});
배포と모니터링
# デプロイ
npx wrangler deploy
# ログの確認
npx wrangler tail
# シークレットの設定
npx wrangler secret put JWT_SECRET
정리
Cloudflare Workersの充実したバインディングとClaude Codeを組み合わせれば、엣지で動作する풀스택APIを효율적으로구축할 수 있습니다。서버리스함수가이드や엣지コンピューティング入門도 참고하세요.
Cloudflare Workers의 상세 정보는Cloudflare Workers공식 문서를 참고하세요.
#Claude Code
#Cloudflare Workers
#edge computing
#serverless
#API
Related Posts
Use Cases
Use Cases
Claude Code로 리팩토링을 자동화하는 방법
Claude Code를 활용해 코드 리팩토링을 효율적으로 자동화하는 방법을 알아봅니다. 실전 프롬프트와 구체적인 리팩토링 패턴을 소개합니다.
Use Cases
Use Cases
Claude Code로 사이드 프로젝트 개발 속도를 극대화하는 방법 [예제 포함]
Claude Code를 활용해 개인 프로젝트 개발 속도를 획기적으로 높이는 방법을 알아봅니다. 실전 예제와 아이디어부터 배포까지의 워크플로를 포함합니다.
Use Cases
Use Cases
Complete CORS Configuration Guide: Claude Code 활용 가이드
complete cors configuration guide: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.