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

Static assets และ framework — เว็บ + API ใน Worker เดียว, React/Astro/Next และ Pages เดิม

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

เป้าหมาย

ต่อยอดเว็บนิ่งจากระดับ 2 ให้เป็น เว็บ + API ใน Worker ตัวเดียว ตั้งค่า SPA/404 ให้ถูก ใส่ header และ redirect ด้วยไฟล์ เลือกวิธี deploy framework (React, Astro, Next.js) และรู้ว่าโปรเจกต์ Pages เดิมควรทำอย่างไรต่อ

ลำดับการทำงานของ request

request ──▶ มีไฟล์ตรง path ใน assets ไหม?
              ├─ มี  → เสิร์ฟไฟล์เลย (ไม่เรียก Worker)
              └─ ไม่มี → ตั้ง not_found_handling ไว้ → ชั้น assets ตอบเอง (404.html / index.html)
                         ไม่ได้ตั้ง → เรียก Worker (ถ้ามี main) หรือ 404 เปล่า
  • ค่าเริ่มต้น ไฟล์มาก่อน — อยากให้โค้ดรันก่อนบาง path (เช่น ตรวจ auth) ใช้ run_worker_first
  • request ที่ได้ไฟล์ static ไม่ได้รันโค้ดของคุณ → ไม่กิน CPU ของ Worker และ ไม่คิดเงิน ไม่จำกัดจำนวน (path ใน run_worker_first นับเป็น request ของ Worker)
  • โหมด SPA มีข้อยกเว้น: เฉพาะ navigation request (เบราว์เซอร์เปิดหน้า มี header Sec-Fetch-Mode: navigate) ที่ได้ index.html — fetch() จากโค้ดหน้าเว็บหรือ curl ธรรมดาไม่ใช่ navigation จึงไปถึง Worker (compatibility_date ≥ 2025-04-01)
  • เพดาน: 20,000 ไฟล์ต่อเวอร์ชัน (Free) / 100,000 (Paid) · ไฟล์ละไม่เกิน 25 MiB

ค่าใน assets

key ค่า ใช้เมื่อ
directory "./public" หรือโฟลเดอร์ build (./dist) ต้องมีเสมอ
binding "ASSETS" อยากเรียก env.ASSETS.fetch(request) จากโค้ด
not_found_handling "single-page-application" React/Vue SPA — path ที่ไม่มีไฟล์ได้ index.html (200)
"404-page" เว็บหลายหน้า — ได้ 404.html ที่ใกล้ที่สุด
"none" (ค่าเริ่ม) ไม่มีไฟล์ → ไป Worker หรือ 404 เปล่า
run_worker_first true หรือ ["/api/*", "!/api/docs/*"] middleware / API ต้องรันก่อน (array สูงสุด 100 รายการ)
html_handling เช่น "auto-trailing-slash" คุม /about vs /about/ vs /about.html

ไฟล์พิเศษในโฟลเดอร์ assets (ใช้ได้เหมือน Pages): _headers, _redirects · .assetsignore (รูปแบบเหมือน .gitignore) กันไม่ให้ไฟล์ไม่ควรขึ้นถูก upload

Pages หรือ Workers

Pages (เดิม) Workers + static assets
สถานะ ยังใช้ได้ ทางหลักสำหรับโปรเจกต์ใหม่ — ฟีเจอร์ใหม่มาที่นี่ก่อน
Cron, Durable Objects ในตัว, Queue consumer, gradual deploy, Tail Workers ❌ ✅
SPA/404 ตรวจจับเอง ต้องตั้ง not_found_handling
โดเมนที่ nameserver ไม่ได้อยู่ Cloudflare ✅ ❌
dev port 8788 (wrangler pages dev) 8787 (wrangler dev)
Functions โฟลเดอร์ functions/ โค้ดใน main (หรือ framework ที่ทำ routing ให้)
ย้ายจาก Pages: pages_build_output_dir → assets.directory, ตั้ง not_found_handling, เพิ่ม binding ถ้าโค้ดใช้ env.ASSETS, ย้ายไฟล์อย่าง _worker.js ออกหรือใส่ใน .assetsignore

Framework

Framework สร้างใหม่ หมายเหตุ
React (Vite) SPA npm create cloudflare@latest -- my-app --framework=react ใช้ Cloudflare Vite plugin → npm run dev รันโค้ด Worker ใน runtime จริง
Astro npm create cloudflare@latest -- my-site --framework=astro หน้าคงที่เสิร์ฟเป็น assets, หน้า SSR รันใน Worker
Next.js npm create cloudflare@latest -- my-next --framework=next ⚠️ Cloudflare แนะนำ vinext เป็นทางหลัก (ยัง beta — รัน compatibility check ก่อนย้ายแอป production) · แอปเดิมที่ใช้ adapter OpenNext (@opennextjs/cloudflare) และติดเรื่องความเข้ากันได้ ใช้ OpenNext ต่อได้
เว็บนิ่งที่ export แล้ว (เช่น Next output: "export") ชี้ assets.directory ไปที่ out/ ง่ายสุด ไม่มีโค้ด server

ลองเลย 🧪

ทดลอง A — เว็บ + API ใน Worker เดียว

cd ~/cloud-ladder
npm create cloudflare@latest -- edge-site --type=hello-world --lang=ts --no-deploy --git
cd edge-site
mkdir -p public
cat > public/index.html <<'EOF'
<!doctype html>
<html lang="th">
<head><meta charset="utf-8"><title>Edge Site</title></head>
<body>
  <h1>เว็บนิ่ง + API</h1>
  <p id="out">กำลังโหลด...</p>
  <script>
    fetch("/api/time").then(r => r.json()).then(d => {
      document.getElementById("out").textContent = `เวลาที่ edge (${d.colo}): ${d.now}`;
    });
  </script>
</body>
</html>
EOF
cat > public/_headers <<'EOF'
/*
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
EOF
cat > public/_redirects <<'EOF'
/home  /  301
EOF

wrangler.jsonc

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "edge-site",
  "main": "src/index.ts",
  "compatibility_date": "2026-09-01",
  "observability": { "enabled": true },
  "assets": {
    "directory": "./public",
    "binding": "ASSETS",
    "not_found_handling": "404-page",
    "run_worker_first": ["/api/*"]
  }
}

src/index.ts

export default {
  async fetch(request, env): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname === "/api/time") {
      return Response.json(
        { now: new Date().toISOString(), colo: request.cf?.colo ?? "local" },
        { headers: { "Cache-Control": "no-store" } },
      );
    }
    if (url.pathname.startsWith("/api/")) {
      return Response.json({ error: "not found" }, { status: 404 });
    }
    return env.ASSETS.fetch(request);   // path อื่นที่หลุดมาถึงโค้ด ส่งคืนให้ชั้น assets
  },
} satisfies ExportedHandler<Env>;
echo '<h1>ไม่พบหน้านี้</h1>' > public/404.html
npx wrangler types && npx wrangler dev

อีก terminal

curl -s http://localhost:8787/api/time
curl -sI http://localhost:8787/ | grep -iE "^HTTP|^x-content-type|^referrer"
curl -sI http://localhost:8787/home | grep -iE "^HTTP|^location"
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8787/nope

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

{"now":"2026-10-09T03:15:00.000Z","colo":"..."}
HTTP/1.1 200 OK
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
HTTP/1.1 301 Moved Permanently
Location: /
404

แล้ว npx wrangler deploy → เปิด URL *.workers.dev เห็นเวลาจาก edge

ทดลอง B — React SPA กับ deep link

cd .. && npm create cloudflare@latest -- spa-demo --framework=react --no-deploy --git
cd spa-demo && grep -A4 '"assets"' wrangler.jsonc

ผลที่ควรเห็น: มี "not_found_handling": "single-page-application" → npm run build && npx wrangler dev แล้ว curl -s -o /dev/null -w "%{http_code}\n" -H "Sec-Fetch-Mode: navigate" http://localhost:8787/some/deep/link ได้ 200 (ได้ index.html ให้ router ฝั่ง client จัดการ — ต้องส่ง header นี้เพื่อจำลองเบราว์เซอร์ ไม่งั้น request ไปถึงโค้ด Worker ของ template) — ลองลบบรรทัดนั้นแล้วรันใหม่ จะได้ 404 (ถ้า template รุ่นที่ได้ใช้คำสั่ง dev/preview ต่างไป ดู scripts ใน package.json)

เก็บกวาด

npx wrangler delete --name edge-site
npx wrangler delete --name spa-demo   # ถ้า deploy ไปแล้ว

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

อาการ สาเหตุ / แก้
รีเฟรชหน้า /dashboard ของ SPA ได้ 404 ไม่ได้ตั้ง not_found_handling: "single-page-application"
เปิด /api/... ตรงในเบราว์เซอร์ได้ index.html แทน JSON SPA mode ตอบ navigation request ด้วย index.html → ใส่ /api/* ใน run_worker_first
env.ASSETS เป็น undefined ไม่ได้ใส่ binding ใน assets
ไฟล์ .env หรือ source map หลุดขึ้น production โฟลเดอร์ assets มีไฟล์ไม่ควรขึ้น → แยกโฟลเดอร์ build / ใช้ .assetsignore
middleware ตรวจ login ไม่ทำงานกับหน้า static ไฟล์ถูกเสิร์ฟก่อนโค้ด → ใส่ path นั้นใน run_worker_first (และนับเป็น invocation)
ย้ายจาก Pages แล้ว dev ที่พอร์ต 8788 ไม่ขึ้น Workers ใช้ wrangler dev ที่ 8787

สรุปจำง่าย

ไฟล์มาก่อนโค้ด — API ใส่ run_worker_first — SPA ต้องตั้ง single-page-application — _headers/_redirects ใช้ได้เหมือน Pages — โปรเจกต์ใหม่ใช้ Workers ไม่ใช่ Pages — Next.js เต็มรูปแบบยังต้องตรวจความเข้ากันได้ก่อน