GodLights Study

3. 첫 Worker 만들기

3.1 프로젝트 생성하기

Cloudflare가 제공하는 공식 스캐폴딩 도구로 새 프로젝트를 만들 수 있습니다.

bash
npm create cloudflare@latest my-first-worker

실행하면 대화형으로 몇 가지를 물어봅니다.

text
What would you like to start with?          → "Hello World" Worker
Which language do you want to use?          → JavaScript (또는 TypeScript)
Do you want to use git for version control?  → Yes
Do you want to deploy your application?      → No (일단 로컬에서 먼저 확인)

생성이 끝나면 아래와 같은 구조가 만들어집니다.

text
my-first-worker/
├── src/
│   └── index.js
├── wrangler.jsonc
├── package.json
└── .gitignore

이 강의의 sample-worker/ 디렉터리도 동일한 구조로 만들어져 있습니다. 직접 새 프로젝트를 만들지 않고 그 폴더를 그대로 실습에 사용해도 됩니다.

3.2 핵심 파일 살펴보기

src/index.js — Worker 코드

js
export default {
  async fetch(request, env, ctx) {
    return new Response("Hello World!");
  },
};

모든 요청은 이 fetch 함수를 거칩니다. 지금은 어떤 요청이 오든 "Hello World!"라는 텍스트를 반환합니다.

wrangler.jsonc — 설정 파일

jsonc
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "my-first-worker",
  "main": "src/index.js",
  "compatibility_date": "2024-11-01"
}

3.3 코드 수정해보기

src/index.js를 열어 아래처럼 바꿔봅시다.

js
export default {
  async fetch(request, env, ctx) {
    return new Response("안녕하세요, 저의 첫 Cloudflare Worker입니다!");
  },
};

저장만 하면 됩니다. 실행은 다음 장에서 wrangler dev로 해봅니다.

참고 자료

➡️ 다음: 로컬에서 개발하고 테스트하기 ⬅️ 이전: 개발 환경 준비하기