본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)48k · #4169

cloudflare-workers

하는 일

Cloudflare Workers는 Cloudflare의 전 세계 네트워크에서 바로 실행되는 작은 코드 프로그램(‘함수’라고 부릅니다)을 만들고 실행하게 해 줍니다. 덕분에 사용자가 어디에 있든 애플리케이션이 매우 빠르게 응답할 수 있습니다.

사용하는 경우

  • ✓매우 빨라야 하는 API(다른 프로그램이 통신에 쓰는 서비스)를 만들 때.
  • ✓요청이 메인 서버에 닿기 전에 보안 검사나 조정을 추가할 때.
  • ✓항상 켜져 있는 서버 없이 특정 시간에 자동 작업을 실행할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/cloudflare-workers/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/cloudflare-workers/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“누군가 접속하면 'Hello World'라고 말하는 간단한 API를 만들어 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

JavaScript나 TypeScript로 코드를 작성하고, Wrangler라는 도구를 사용해 그 코드를 Cloudflare 네트워크로 보냅니다. 그다음 Cloudflare가 사용자 가까이에서 코드를 실행하는 일을 맡습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Cloudflare Workers

Deploy JavaScript and TypeScript functions to Cloudflare's global edge network with sub-millisecond cold starts.

When to Use

  • Building lightweight APIs and microservices at the edge.
  • Adding middleware (auth, rate limiting, header injection) in front of origin servers.
  • Running cron jobs on a schedule without maintaining infrastructure.
  • Processing webhooks, image transformations, or A/B testing logic.
  • Serving dynamic content from KV, D1, or R2 storage bindings.

Prerequisites

  • Node.js 18+ installed locally.
  • Wrangler CLI: npm install -g wrangler.
  • Cloudflare account (free plan supports 100,000 requests/day).
  • Authenticated: wrangler login or set CLOUDFLARE_API_TOKEN.

Quick Start

# Scaffold a new Worker project
npm create cloudflare@latest my-worker
cd my-worker

# Login to Cloudflare
npx wrangler login

# Start local development server (port 8787)
npx wrangler dev

# Deploy to production
npx wrangler deploy

Essential Wrangler Commands

# Local development with remote bindings (KV, D1, R2)
npx wrangler dev --remote

# Deploy to a specific environment
npx wrangler deploy --env staging

# Set a secret (prompts for value)
npx wrangler secret put API_TOKEN
npx wrangler secret put API_TOKEN --env staging

# List secrets
npx wrangler secret list

# Tail production logs in real time
npx wrangler tail

# Tail with filters
npx wrangler tail --status=error --search="timeout"

# View deployment versions
npx wrangler deployments list

# Rollback to a previous deployment
npx wrangler rollback

Wrangler Configuration

# wrangler.toml
name = "my-api"
main = "src/index.ts"
compatibility_date = "2024-09-01"
compatibility_flags = ["nodejs_compat"]

# Custom routes
routes = [
  { pattern = "api.example.com/*", zone_name = "example.com" }
]

# Or use a workers.dev subdomain
# workers_dev = true

# Environment variables (non-secret)
[vars]
ENVIRONMENT = "production"
API_VERSION = "v2"

# Staging environment override
[env.staging]
name = "my-api-staging"
routes = [
  { pattern = "api-staging.example.com/*", zone_name = "example.com" }
]
[env.staging.vars]
ENVIRONMENT = "staging"

Worker Examples

Basic API Router

// src/index.ts
export interface Env {
  ENVIRONMENT: string;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);

    switch (url.pathname) {
      case "/":
        return new Response("OK", { status: 200 });

      case "/api/health":
        return Response.json({
          status: "healthy",
          env: env.ENVIRONMENT,
          timestamp: new Date().toISOString(),
        });

      case "/api/data":
        if (request.method !== "POST") {
          return new Response("Method Not Allowed", { status: 405 });
        }
        const body = await request.json();
        // Process in the background after returning response
        ctx.waitUntil(logToAnalytics(body));
        return Response.json({ received: true });

      default:
        return new Response("Not Found", { status: 404 });
    }
  },
};

async function logToAnalytics(data: unknown): Promise<void> {
  await fetch("https://analytics.example.com/ingest", {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
}

Middleware: Rate Limiting with KV

// src/rate-limiter.ts
interface Env {
  RATE_LIMIT_KV: KVNamespace;
  ORIGIN_URL: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const ip = request.headers.get("CF-Connecting-IP") || "unknown";
    const key = `ratelimit:${ip}`;
    const window = 60; // seconds
    const maxRequests = 100;

    const current = parseInt((await env.RATE_LIMIT_KV.get(key)) || "0");

    if (current >= maxRequests) {
      return new Response("Too Many Requests", {
        status: 429,
        headers: { "Retry-After": String(window) },
      });
    }

    await env.RATE_LIMIT_KV.put(key, String(current + 1), {
      expirationTtl: window,
    });

    // Forward to origin
    const originRequest = new Request(env.ORIGIN_URL + new URL(request.url).pathname, request);
    return fetch(originRequest);
  },
};

KV Storage Binding

# wrangler.toml
[[kv_namespaces]]
binding = "MY_KV"
id = "abc123def456"

# Preview namespace for local dev
[[kv_namespaces]]
binding = "MY_KV"
id = "abc123def456"

…
자주 묻는 질문

Cloudflare Workers를 쓰려면 돈을 내야 하나요?

Cloudflare의 무료 요금제는 하루 요청 수가 넉넉해서, 작은 프로젝트나 테스트에 충분한 경우가 많습니다.

‘엣지(edge)’는 무슨 뜻인가요?

Cloudflare가 전 세계에 서버를 둔 물리적 위치를 말합니다. 엣지에서 코드를 실행하면 최종 사용자에게 더 가까이에서 실행되어 모든 것이 빨라집니다.

‘콜드 스타트’란 무엇인가요?

일정 기간 사용되지 않은 뒤 코드가 처음 실행될 때 생길 수 있는 짧은 지연입니다. Cloudflare Workers는 콜드 스타트가 매우 빠르고 거의 느껴지지 않는 것으로 알려져 있습니다.

상세 정보

작성자의 원본 설명

Build and deploy edge functions with Cloudflare Workers and Wrangler. Use for APIs, cron jobs, and edge middleware.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#4169
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬