SiamCafe.net Blog
Technology

Netlify Edge Troubleshooting แก้ปัญหา

netlify edge troubleshooting แกปญหา
Netlify Edge Troubleshooting แก้ปัญหา | SiamCafe Blog
2025-08-30· อ. บอม — SiamCafe.net· 1,399 คำ

Netlify Edge Troubleshooting แก้ปัญหา คืออะไร

Netlify Edge เป็น edge computing platform ที่รัน serverless functions บน CDN edge nodes ทั่วโลก ช่วยให้เว็บไซต์โหลดเร็วขึ้นโดยประมวลผลใกล้ผู้ใช้ แต่การพัฒนาบน edge มีความท้าทายเฉพาะตัว เช่น cold start latency, runtime limitations, caching issues และ deployment errors บทความนี้รวบรวมปัญหาที่พบบ่อยใน Netlify Edge Functions, Build Failures, DNS/SSL issues และวิธีแก้ไขแบบ step-by-step สำหรับนักพัฒนาไทย

ปัญหาที่พบบ่อย

# common_issues.py — Common Netlify Edge issues
import json

class CommonIssues:
    ISSUES = {
        "build_fail": {
            "name": "Build Failed",
            "symptoms": ["Deploy fails with exit code 1", "Build timeout (> 30 min)", "Module not found errors"],
            "causes": ["Dependency version mismatch", "Missing environment variables", "Node.js version incompatible"],
            "frequency": "Very Common",
        },
        "edge_function_error": {
            "name": "Edge Function Errors",
            "symptoms": ["502 Bad Gateway", "Function timeout", "Runtime errors in logs"],
            "causes": ["Deno runtime limitations", "Unsupported Node.js APIs", "Memory limit exceeded"],
            "frequency": "Common",
        },
        "dns_ssl": {
            "name": "DNS / SSL Issues",
            "symptoms": ["Custom domain not working", "SSL certificate pending", "ERR_CERT_AUTHORITY_INVALID"],
            "causes": ["DNS propagation delay", "Incorrect DNS records", "CAA record blocking"],
            "frequency": "Common",
        },
        "caching": {
            "name": "Caching Problems",
            "symptoms": ["Old content showing after deploy", "Stale API responses", "Inconsistent content across regions"],
            "causes": ["CDN cache not purged", "Browser cache", "Missing cache headers"],
            "frequency": "Moderate",
        },
        "redirect_rewrite": {
            "name": "Redirect / Rewrite Issues",
            "symptoms": ["404 on client-side routes (SPA)", "Infinite redirect loop", "Wrong redirect destination"],
            "causes": ["Missing _redirects file", "netlify.toml config error", "Conflicting rules"],
            "frequency": "Common",
        },
    }

    def show_issues(self):
        print("=== Common Netlify Issues ===\n")
        for key, issue in self.ISSUES.items():
            print(f"[{issue['name']}] ({issue['frequency']})")
            print(f"  Symptoms: {', '.join(issue['symptoms'][:2])}")
            print(f"  Causes: {', '.join(issue['causes'][:2])}")
            print()

issues = CommonIssues()
issues.show_issues()

Build Troubleshooting

# build_debug.py — Build failure debugging
import json

class BuildDebug:
    SOLUTIONS = {
        "node_version": {
            "problem": "Node.js version mismatch",
            "error": "error engine \"node\" is incompatible",
            "fix": """
# .nvmrc — กำหนด Node version
18

# หรือ netlify.toml
[build.environment]
  NODE_VERSION = "18"
  NPM_VERSION = "9"
""",
        },
        "dependency": {
            "problem": "Dependency installation fails",
            "error": "npm ERR! peer dep missing / ERESOLVE",
            "fix": """
# Option 1: ใช้ legacy peer deps
[build.environment]
  NPM_FLAGS = "--legacy-peer-deps"

# Option 2: Clear cache
# Netlify Dashboard → Deploys → Trigger Deploy → Clear cache and deploy

# Option 3: ใช้ CI=true
[build.environment]
  CI = ""
""",
        },
        "memory": {
            "problem": "Build out of memory",
            "error": "JavaScript heap out of memory",
            "fix": """
[build.environment]
  NODE_OPTIONS = "--max-old-space-size=4096"
""",
        },
        "timeout": {
            "problem": "Build timeout (> 30 min)",
            "error": "Build exceeded maximum allowed runtime",
            "fix": """
# ลด build time:
# 1. ใช้ incremental builds (Next.js ISR)
# 2. Cache dependencies (node_modules)
# 3. Optimize images at build time
# 4. ลดจำนวน pages ที่ generate (SSG)

# netlify.toml — cache plugin
[[plugins]]
  package = "netlify-plugin-cache"
  [plugins.inputs]
    paths = ["node_modules", ".next/cache"]
""",
        },
    }

    def show_solutions(self):
        print("=== Build Solutions ===\n")
        for key, sol in self.SOLUTIONS.items():
            print(f"[{sol['problem']}]")
            print(f"  Error: {sol['error']}")
            print(f"  Fix: {sol['fix'][:200].strip()}")
            print()

build = BuildDebug()
build.show_solutions()

Edge Functions Debugging

# edge_debug.py — Edge Functions troubleshooting
import json
import random

class EdgeFunctionsDebug:
    DENO_ISSUES = {
        "node_api": {
            "problem": "Node.js API ใช้ไม่ได้ใน Edge Functions",
            "error": "ReferenceError: process is not defined",
            "fix": "Edge Functions ใช้ Deno runtime ไม่ใช่ Node.js. ใช้ Deno APIs หรือ Web APIs แทน",
            "example": "แทน process.env.KEY → Netlify.env.get('KEY')",
        },
        "import": {
            "problem": "Import errors",
            "error": "Module not found / Cannot resolve module",
            "fix": "ใช้ URL imports สำหรับ Deno หรือ npm: prefix",
            "example": 'import { something } from "npm:package-name";',
        },
        "timeout": {
            "problem": "Edge Function timeout",
            "error": "Function execution timed out (50s limit)",
            "fix": "ลด execution time: cache results, reduce external calls, ใช้ streaming",
            "example": "ใช้ Response streaming แทนรอ full response",
        },
    }

    EDGE_FUNCTION_EXAMPLE = """
// netlify/edge-functions/hello.ts — Edge Function example
import type { Context } from "@netlify/edge-functions";

export default async (request: Request, context: Context) => {
  try {
    const url = new URL(request.url);
    const country = context.geo.country?.code || "unknown";
    
    // Debug logging
    console.log(`Request from : `);
    
    // Edge-side logic
    if (country === "TH") {
      return new Response("สวัสดี! Welcome from Thailand", {
        headers: { "content-type": "text/html; charset=utf-8" }
      });
    }
    
    return context.next();  // Pass to origin
  } catch (error) {
    console.error("Edge function error:", error);
    return new Response("Internal Error", { status: 500 });
  }
};

export const config = { path: "/api/*" };
"""

    def show_issues(self):
        print("=== Edge Function Issues ===\n")
        for key, issue in self.DENO_ISSUES.items():
            print(f"[{issue['problem']}]")
            print(f"  Error: {issue['error']}")
            print(f"  Fix: {issue['fix']}")
            print()

    def show_example(self):
        print("=== Edge Function Example ===")
        print(self.EDGE_FUNCTION_EXAMPLE[:500])

edge = EdgeFunctionsDebug()
edge.show_issues()
edge.show_example()

DNS & SSL Troubleshooting

# dns_ssl.py — DNS and SSL debugging
import json
import random

class DNSSSLDebug:
    DNS_FIXES = {
        "custom_domain": {
            "problem": "Custom domain ไม่ทำงาน",
            "steps": [
                "1. ตรวจ DNS records: dig example.com",
                "2. CNAME → your-site.netlify.app (subdomain)",
                "3. A record → 75.2.60.5 (apex domain)",
                "4. AAAA record → Netlify IPv6 (optional)",
                "5. รอ DNS propagation (5 min - 48 hrs)",
            ],
        },
        "ssl_pending": {
            "problem": "SSL Certificate stuck at pending",
            "steps": [
                "1. ตรวจ DNS ชี้มา Netlify ถูกต้อง",
                "2. ตรวจ CAA record (ต้อง allow letsencrypt.org)",
                "3. Netlify Dashboard → Domain → Renew certificate",
                "4. ลบ domain แล้วเพิ่มใหม่",
                "5. รอ 24 ชั่วโมง (Let's Encrypt rate limit)",
            ],
        },
        "mixed_content": {
            "problem": "Mixed Content warnings",
            "steps": [
                "1. ตรวจ HTTP links ใน HTML/CSS/JS",
                "2. เปลี่ยนเป็น HTTPS หรือ // (protocol-relative)",
                "3. เพิ่ม CSP header: upgrade-insecure-requests",
            ],
        },
    }

    DEBUG_COMMANDS = """
# DNS Debugging Commands
dig example.com A           # ตรวจ A record
dig example.com CNAME       # ตรวจ CNAME
dig example.com CAA         # ตรวจ CAA record
nslookup example.com       # Alternative DNS lookup
curl -I https://example.com # ตรวจ HTTP headers + SSL

# Online Tools
# - dnschecker.org (propagation check)
# - ssllabs.com/ssltest (SSL test)
# - whatsmydns.net (DNS propagation)
"""

    def show_fixes(self):
        print("=== DNS/SSL Fixes ===\n")
        for key, fix in self.DNS_FIXES.items():
            print(f"[{fix['problem']}]")
            for step in fix["steps"][:4]:
                print(f"  {step}")
            print()

    def show_commands(self):
        print("=== Debug Commands ===")
        print(self.DEBUG_COMMANDS[:400])

dns = DNSSSLDebug()
dns.show_fixes()
dns.show_commands()

Performance & Caching

# performance.py — Performance optimization
import json
import random

class PerformanceOptimization:
    CACHE_HEADERS = """
# netlify.toml — Cache headers configuration
[[headers]]
  for = "/assets/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

[[headers]]
  for = "/*.html"
  [headers.values]
    Cache-Control = "public, max-age=0, must-revalidate"

[[headers]]
  for = "/api/*"
  [headers.values]
    Cache-Control = "no-cache, no-store"
    Netlify-CDN-Cache-Control = "public, max-age=60, stale-while-revalidate=300"

# _headers file alternative
/assets/*
  Cache-Control: public, max-age=31536000, immutable

/*.html
  Cache-Control: public, max-age=0, must-revalidate
"""

    TIPS = {
        "image_optimization": "ใช้ Netlify Image CDN: /_ipx/ endpoint สำหรับ resize/format",
        "asset_hashing": "ใช้ content hashing ใน filename สำหรับ long-term caching",
        "prerender": "ใช้ Prerendering สำหรับ SPA (Netlify settings → Prerendering)",
        "bundle_size": "ตรวจ bundle size: npx webpack-bundle-analyzer",
        "edge_cache": "ใช้ Netlify-CDN-Cache-Control header สำหรับ edge caching",
    }

    def show_headers(self):
        print("=== Cache Headers Config ===")
        print(self.CACHE_HEADERS[:400])

    def show_tips(self):
        print(f"\n=== Performance Tips ===")
        for tip, detail in self.TIPS.items():
            print(f"  [{tip}] {detail}")

    def lighthouse(self):
        print(f"\n=== Lighthouse Scores ===")
        scores = {
            "Performance": random.randint(85, 100),
            "Accessibility": random.randint(90, 100),
            "Best Practices": random.randint(90, 100),
            "SEO": random.randint(90, 100),
        }
        for metric, score in scores.items():
            bar = "█" * (score // 5)
            print(f"  {metric:<18} {score}/100 {bar}")

perf = PerformanceOptimization()
perf.show_headers()
perf.show_tips()
perf.lighthouse()

FAQ - คำถามที่พบบ่อย

Q: Build failed แต่ไม่รู้สาเหตุ ทำอย่างไร?

A: 1. ดู build log ใน Netlify Dashboard → Deploys → คลิก deploy ที่ fail 2. ลอง build locally: npm run build 3. ตรวจ Node version (.nvmrc) 4. Clear cache and deploy ใหม่ 5. ตรวจ environment variables ครับหรือือไม่

Q: Edge Functions กับ Serverless Functions ต่างกันอย่างไร?

A: Edge Functions: รันบน Deno runtime, ใกล้ผู้ใช้ (edge nodes), เร็วกว่า, จำกัด API Serverless Functions: รันบน Node.js, region เดียว (us-east-1), full Node.js API ใช้ Edge: geolocation, A/B testing, personalization, headers manipulation ใช้ Serverless: database access, complex logic, Node.js libraries

Q: Deploy สำเร็จแต่เว็บแสดงเนื้อหาเก่า?

A: 1. Clear browser cache (Ctrl+Shift+R) 2. ตรวจ cache headers ใน netlify.toml 3. ใช้ Netlify Dashboard → Clear CDN cache 4. ตรวจว่า build output ถูกต้อง (publish directory) 5. ถ้าใช้ SPA: ตรวจ _redirects หรือ netlify.toml redirects

Q: SPA (React/Vue) แสดง 404 เมื่อ refresh?

A: เพิ่ม redirect rule สำหรับ client-side routing: ไฟล์ _redirects: /* /index.html 200 หรือ netlify.toml: [[redirects]] from = "/*" to = "/index.html" status = 200 ทำให้ทุก route ถูก serve ด้วย index.html แล้วให้ router จัดการ

📖 บทความที่เกี่ยวข้อง

Netlify Edge IoT Gatewayอ่านบทความ → PostgreSQL JSONB Troubleshooting แก้ปัญหาอ่านบทความ → Netlify Edge Progressive Deliveryอ่านบทความ → WebSocket Scaling Troubleshooting แก้ปัญหาอ่านบทความ → Netlify Edge High Availability HA Setupอ่านบทความ →

📚 ดูบทความทั้งหมด →