Cloudflare Workers
Cloudflare Workers (Edge Serverless Platform)
Cloudflare's edge computing platform. Fast startup with V8 isolates. Runs in 300+ data centers worldwide.
Cloudflare Workers (Edge Serverless Platform)
Cloudflare's edge computing platform. Fast startup with V8 isolates. Runs in 300+ data centers worldwide.
Cloudflare Workers is a serverless edge computing platform that runs JavaScript/TypeScript code in Cloudflare's more than 300 data centers worldwide. Unlike traditional Lambda or Cloud Functions, code runs on the edge server closest to the user.
Workers uses the isolates technology of the Chrome V8 engine. By using lightweight isolates instead of containers or VMs, it provides start-up times of around 0ms with no cold starts. Thousands of isolates can run simultaneously within a single process, making it extremely efficient.
Key features:
// src/index.ts - 기본 Cloudflare Worker
export interface Env {
API_KEY: string;
CACHE_TTL: string;
}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const url = new URL(request.url);
// CORS 헤더 설정
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
// Preflight 요청 처리
if (request.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
// 라우팅
if (url.pathname === '/api/hello') {
return new Response(
JSON.stringify({
message: 'Hello from the Edge!',
location: request.cf?.city || 'Unknown',
country: request.cf?.country || 'Unknown',
timestamp: new Date().toISOString(),
}),
{
headers: {
'Content-Type': 'application/json',
...corsHeaders,
},
}
);
}
// 캐시된 응답 반환
if (url.pathname === '/api/cached') {
const cacheKey = new Request(url.toString(), request);
const cache = caches.default;
let response = await cache.match(cacheKey);
if (!response) {
response = new Response(
JSON.stringify({ data: 'Fresh data', time: Date.now() }),
{
headers: {
'Content-Type': 'application/json',
'Cache-Control': `s-maxage=${env.CACHE_TTL}`,
},
}
);
ctx.waitUntil(cache.put(cacheKey, response.clone()));
}
return response;
}
return new Response('Not Found', { status: 404 });
},
};
// src/index.ts - Hono 프레임워크를 사용한 API 라우터
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { cache } from 'hono/cache';
import { jwt } from 'hono/jwt';
type Bindings = {
JWT_SECRET: string;
DATABASE: D1Database;
RATE_LIMITER: RateLimit;
};
const app = new Hono<{ Bindings: Bindings }>();
// 미들웨어 설정
app.use('/*', cors());
app.use('/api/*', async (c, next) => {
// Rate Limiting
const { success } = await c.env.RATE_LIMITER.limit({
key: c.req.header('CF-Connecting-IP') || 'anonymous',
});
if (!success) {
return c.json({ error: 'Rate limit exceeded' }, 429);
}
await next();
});
// 공개 엔드포인트
app.get('/', (c) => c.json({ status: 'healthy', edge: c.req.raw.cf?.colo }));
// JWT 인증이 필요한 엔드포인트
app.use('/api/protected/*', jwt({ secret: (c) => c.env.JWT_SECRET }));
// D1 데이터베이스 조회
app.get('/api/users', async (c) => {
const { results } = await c.env.DATABASE.prepare(
'SELECT id, name, email FROM users LIMIT 100'
).all();
return c.json(results);
});
// 사용자 생성
app.post('/api/users', async (c) => {
const body = await c.req.json();
const { name, email } = body;
const result = await c.env.DATABASE.prepare(
'INSERT INTO users (name, email) VALUES (?, ?) RETURNING id'
).bind(name, email).first();
return c.json({ id: result?.id, name, email }, 201);
});
// 캐시된 응답 (1시간)
app.get(
'/api/cached-data',
cache({ cacheName: 'api-cache', cacheControl: 'max-age=3600' }),
(c) => c.json({ data: 'This is cached for 1 hour' })
);
export default app;
// src/kv-session.ts - Workers KV를 사용한 세션 관리
export interface Env {
SESSIONS: KVNamespace;
SESSION_TTL: string;
}
interface Session {
userId: string;
email: string;
roles: string[];
createdAt: number;
expiresAt: number;
}
// 세션 생성
export async function createSession(
env: Env,
userId: string,
email: string,
roles: string[]
): Promise<string> {
const sessionId = crypto.randomUUID();
const ttl = parseInt(env.SESSION_TTL) || 3600;
const session: Session = {
userId,
email,
roles,
createdAt: Date.now(),
expiresAt: Date.now() + ttl * 1000,
};
// KV에 세션 저장 (TTL 자동 만료)
await env.SESSIONS.put(
`session:${sessionId}`,
JSON.stringify(session),
{ expirationTtl: ttl }
);
return sessionId;
}
// 세션 조회
export async function getSession(
env: Env,
sessionId: string
): Promise<Session | null> {
const data = await env.SESSIONS.get(`session:${sessionId}`);
if (!data) return null;
const session: Session = JSON.parse(data);
// 만료 확인
if (session.expiresAt < Date.now()) {
await env.SESSIONS.delete(`session:${sessionId}`);
return null;
}
return session;
}
// 세션 갱신
export async function refreshSession(
env: Env,
sessionId: string
): Promise<boolean> {
const session = await getSession(env, sessionId);
if (!session) return false;
const ttl = parseInt(env.SESSION_TTL) || 3600;
session.expiresAt = Date.now() + ttl * 1000;
await env.SESSIONS.put(
`session:${sessionId}`,
JSON.stringify(session),
{ expirationTtl: ttl }
);
return true;
}
// 세션 삭제 (로그아웃)
export async function deleteSession(
env: Env,
sessionId: string
): Promise<void> {
await env.SESSIONS.delete(`session:${sessionId}`);
}
// wrangler.toml 설정 예시
/*
name = "session-api"
main = "src/index.ts"
compatibility_date = "2024-01-01"
kv_namespaces = [
{ binding = "SESSIONS", id = "abc123..." }
]
[vars]
SESSION_TTL = "7200"
*/
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
The Free plan has a CPU time limit of 10ms per request, and Paid has 30ms. Don't process heavy computation (image processing, parsing large JSON) directly in the Worker; delegate it to the origin server. ctx.waitUntil() runs after the response is sent, but the limit still applies.
Workers KV is replicated globally but is eventually consistent. If you read from another region immediately after writing data, an old version may be returned. Use Durable Objects if you need strong consistency.
Workers is optimized for lightweight logic such as authentication/authorization, cache lookups, request routing, and header manipulation. Handle DB queries and complex business logic at the origin, and use Workers as an edge proxy/cache layer.