ระดับ 4c · บทที่ 5/5

โดเมน, routes, Cron Triggers และ environments

⏱ 50 นาทีลองในCloudflare ↗

เป้าหมาย

เอา Worker ขึ้นโดเมนจริงด้วยวิธีที่ถูก (Custom Domain หรือ Route) ปิด URL workers.dev ที่ไม่ต้องใช้ ตั้งงานตามเวลาด้วย Cron Triggers และแยก staging / production ด้วย environments ในไฟล์ config เดียว

3 ทางเข้าของ Worker

*.workers.dev Custom Domain Route
ตัวอย่าง api.ton.workers.dev api.example.com example.com/api/*
ครอบ ทั้ง Worker ทุก path ของ hostname นั้น เฉพาะ pattern (มี * ได้)
DNS + cert มีให้ สร้างให้อัตโนมัติ ต้องมี DNS record แบบ proxied อยู่ก่อน
มี origin ข้างหลัง ไม่มี ไม่มี — Worker คือปลายทาง มีได้ — Worker เรียก fetch(request) ส่งต่อ origin
ใช้เมื่อ dev/ทดสอบ API/เว็บที่ Worker เป็นเจ้าของทั้งโฮสต์ แทรก Worker หน้าเว็บเดิมบาง path (เช่น หน้า ALB)
  • Custom Domain สร้างไม่ได้ถ้า hostname มี CNAME record อยู่แล้ว → ลบ record เดิมก่อน
  • Custom Domain ไม่รองรับ wildcard hostname (*.example.com) → ใช้ Route
  • production ควรตั้ง "workers_dev": false เพื่อไม่ให้มีทางเข้าที่ข้าม WAF/Rules ของโซน

Cron Triggers

"triggers": { "crons": ["*/5 * * * *", "0 1 * * *"] }
async scheduled(controller, env, ctx) {
  // controller.cron = pattern ที่ทำให้รอบนี้รัน, controller.scheduledTime = เวลา (ms)
}
เรื่อง ค่า
เขตเวลา UTC เสมอ — 08:00 ไทย = 0 1 * * *
เพิ่ม/แก้แล้วมีผล ภายในหลายนาที (สูงสุดราว 15 นาที)
จำนวนต่อบัญชี Free 5 · Paid 250
CPU ต่อรอบ Free 10 ms · Paid 30 s (รอบถี่กว่า 1 ชม.) / 15 นาที (รอบ ≥ 1 ชม.)
  • งานต้อง idempotent — รันซ้ำแล้วผลไม่เพี้ยน (ระบบอาจรันช้าหรือซ้ำได้)
  • ทดสอบในเครื่อง: wrangler dev แล้วยิง /cdn-cgi/local/scheduled?cron=...
  • ลบ cron ทั้งหมด: ตั้ง "crons": [] แล้ว deploy

Environments — staging/production ในไฟล์เดียว

{
  "name": "status-edge",            // production
  "vars": { "STAGE": "production" },
  "env": {
    "staging": {                     // deploy → ชื่อ Worker = status-edge-staging
      "vars": { "STAGE": "staging" },
      "kv_namespaces": [ ... ]       // ต้องประกาศซ้ำ
    }
  }
}
ประเภท key ตัวอย่าง ใน env.<ชื่อ>
inheritable main, compatibility_date, compatibility_flags, observability ได้จากบนสุดอัตโนมัติ (override ได้)
non-inheritable vars, kv_namespaces, r2_buckets, d1_databases, services, queues, durable_objects ต้องประกาศซ้ำทุก env ไม่งั้นไม่มี
routes / triggers routes, triggers ตั้งแยกต่อ env (staging ไม่ควรใช้โดเมน production)
  • deploy: npx wrangler deploy --env staging · ไม่ใส่ --env = production (ค่าบนสุด)
  • secret แยกต่อ env: npx wrangler secret put KEY --env staging · dev ใช้ .dev.vars.staging
  • staging ใช้ KV/D1 คนละตัวกับ production เสมอ

ลองเลย 🧪

ต้องมีโดเมนบน Cloudflare (ระดับ 2) — แทน example.com ด้วยโดเมนคุณ และ hostname status / status-staging ต้อง ยังไม่มี DNS record

ทดลอง A — โปรเจกต์ + KV สองชุด (prod/staging)

cd ~/cloud-ladder
npm create cloudflare@latest -- status-edge --type=hello-world --lang=ts --no-deploy --git
cd status-edge
npx wrangler kv namespace create STATUS
npx wrangler kv namespace create STATUS_STAGING

wrangler.jsonc (ใส่ id ทั้งสองตัวที่ได้)

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "status-edge",
  "main": "src/index.ts",
  "compatibility_date": "2026-09-01",
  "observability": { "enabled": true },
  "workers_dev": false,
  "routes": [{ "pattern": "status.example.com", "custom_domain": true }],
  "triggers": { "crons": ["*/5 * * * *"] },
  "vars": { "STAGE": "production", "CHECK_URL": "https://example.com/" },
  "kv_namespaces": [{ "binding": "STATUS", "id": "[PROD_KV_ID]" }],
  "env": {
    "staging": {
      "workers_dev": true,
      "routes": [{ "pattern": "status-staging.example.com", "custom_domain": true }],
      "triggers": { "crons": ["*/30 * * * *"] },
      "vars": { "STAGE": "staging", "CHECK_URL": "https://example.com/" },
      "kv_namespaces": [{ "binding": "STATUS", "id": "[STAGING_KV_ID]" }]
    }
  }
}

ทดลอง B — Worker ที่ตรวจเว็บทุก 5 นาที แล้วโชว์ผลล่าสุด แทนที่ src/index.ts

interface Check { stage: string; url: string; status: number; ms: number; at: string; cron: string }

export default {
  async scheduled(controller, env, ctx): Promise<void> {
    const started = Date.now();
    let status = 0;
    try {
      const res = await fetch(env.CHECK_URL, { method: "HEAD", redirect: "manual" });
      status = res.status;
    } catch (err) {
      console.error(JSON.stringify({ event: "check_failed", error: String(err) }));
    }
    const check: Check = {
      stage: env.STAGE,
      url: env.CHECK_URL,
      status,
      ms: Date.now() - started,
      at: new Date(controller.scheduledTime).toISOString(),
      cron: controller.cron,
    };
    // key เดียว เขียนรอบละครั้ง (ห่างกันหลายนาที) — อยู่ในเพดาน 1 write/วินาที/key และ 1,000 writes/วัน ของ Free
    ctx.waitUntil(env.STATUS.put("latest", JSON.stringify(check)));
    console.log(JSON.stringify({ event: "check", ...check }));
  },

  async fetch(request, env): Promise<Response> {
    const latest = await env.STATUS.get<Check>("latest", "json");
    return Response.json(latest ?? { stage: env.STAGE, message: "ยังไม่มีผลตรวจ รอรอบ cron แรก" });
  },
} satisfies ExportedHandler<Env>;
npx wrangler types && npx tsc --noEmit && npx wrangler dev

อีก terminal — จำลองรอบ cron แล้วอ่านผล

curl -s "http://localhost:8787/cdn-cgi/local/scheduled?cron=*/5+*+*+*+*"
curl -s http://localhost:8787/

ผลที่ควรเห็น:

Ran scheduled event
{"stage":"production","url":"https://example.com/","status":200,"ms":143,"at":"2026-10-09T...","cron":"*/5 * * * *"}

(ข้อความบรรทัดแรกอาจต่างตามรุ่น wrangler · ถ้ารุ่นเก่าไม่รู้จัก path นี้ ให้รัน npx wrangler dev --test-scheduled แล้วใช้ /__scheduled?cron=... แทน)

ทดลอง C — deploy staging ก่อน แล้วค่อย production

npx wrangler deploy --env staging
curl -s https://status-staging.example.com/
npx wrangler deploy
curl -s https://status.example.com/
curl -s -o /dev/null -w "%{http_code}\n" https://status-edge.[your-subdomain].workers.dev/

ผลที่ควรเห็น:

... Deployed status-edge-staging triggers
  status-staging.example.com (custom domain)
  schedule: */30 * * * *
{"stage":"staging","message":"ยังไม่มีผลตรวจ รอรอบ cron แรก"}
... Deployed status-edge triggers
  status.example.com (custom domain)
  schedule: */5 * * * *
{"stage":"production",...}
000   (หรือ 404 — production ปิด workers.dev แล้ว)

รอ 5–15 นาที แล้ว curl -s https://status.example.com/ จะเห็นผลจาก cron จริง · ดู log: npx wrangler tail --format pretty (cert ของ custom domain อาจใช้เวลาสักครู่ — ถ้า curl ได้ TLS error ให้รอแล้วลองใหม่)

เก็บกวาด (cron นับโควตา 5 ตัวต่อบัญชีบน Free — อย่าทิ้งไว้ถ้าไม่ใช้)

npx wrangler delete --env staging
npx wrangler delete
npx wrangler kv namespace delete --namespace-id [PROD_KV_ID]
npx wrangler kv namespace delete --namespace-id [STAGING_KV_ID]

ลบ Worker แล้ว custom domain และ DNS record ที่ระบบสร้างให้จะถูกถอดออกด้วย — ตรวจในหน้า DNS ว่าไม่เหลือ record status*

กับดักที่เจอบ่อย

อาการ สาเหตุ / แก้
deploy custom domain error ว่ามี record อยู่แล้ว hostname มี CNAME เดิม → ลบ record ก่อน
Route ไม่ทำงาน ได้ error DNS Route ต้องมี DNS record proxied ของ hostname นั้น (ไม่มี origin ใช้ A 192.0.2.1 ส้ม)
cron ทำงานผิดเวลา 7 ชั่วโมง cron เป็น UTC → ลบ 7 ชั่วโมงจากเวลาไทย
แก้ cron แล้วยังรันตามเดิม การเปลี่ยนแปลงใช้เวลาถึง ~15 นาที
staging ไม่มี env.STATUS bindings/vars ไม่สืบทอด → ประกาศใน env.staging ด้วย และรัน wrangler types
staging เขียนทับข้อมูล production ใช้ namespace id เดียวกัน → แยก KV/D1 ต่อ env เสมอ
คนยิงตรง *.workers.dev ข้าม WAF ตั้ง "workers_dev": false ใน production

สรุปจำง่าย

Worker เป็นเจ้าของทั้งโฮสต์ = Custom Domain, แทรกบาง path หน้า origin = Route — production ปิด workers.dev — cron เป็น UTC และต้อง idempotent — bindings/vars ไม่สืบทอดข้าม env — staging ใช้ข้อมูลคนละชุด และ deploy staging ก่อนเสมอ