ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge
เลือก Node หรือ Edge ต่อเส้นทางตามเวลาการเริ่มทำงานเมื่อแคชว่าง API ที่ใช้ได้ และเวลาแฝงตามภูมิศาสตร์
ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge เป็นบทเรียน Next.js 15 Fullstack (App Router + Server Actions) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack (App Router + Server Actions) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Two Runtimes, One Route Handler
In Next.js 15, every Route Handler (app/api/.../route.ts) runs on one of two runtimes: the Node.js runtime (the default) or the Edge runtime.
- Node runtime — a full Node.js server. Access to all Node APIs, npm packages, file system, TCP sockets.
- Edge runtime — a lightweight V8-based environment (Web APIs only) that deploys to many locations close to your users.
You pick the runtime per route with a single export, so different endpoints in the same app can use different runtimes.
// app/api/hello/route.ts
import { NextResponse } from 'next/server';
// Opt this route into the Edge runtime
export const runtime = 'edge';
export async function GET() {
return NextResponse.json({ message: 'Hello from the Edge' });
}The Default Is Node
If you do not set runtime, the handler runs on the Node.js runtime. This is the safe default for most fullstack work because it supports your database drivers, ORMs (Prisma, Drizzle), and any npm library.
You only opt into Edge when its specific benefits (low latency, fast cold starts, geographic distribution) matter more than the APIs you'd give up.
// app/api/users/route.ts
import { NextResponse } from 'next/server';
import { db } from '@/lib/db'; // e.g. Prisma / Drizzle
// No runtime export => Node.js runtime (default)
export async function GET() {
const users = await db.user.findMany();
return NextResponse.json(users);
}Cold Starts: Why Edge Feels Faster
A cold start is the delay when a serverless function has to boot before handling a request.
- Node functions boot a Node.js process — heavier, slower cold starts (often tens to hundreds of ms).
- Edge functions run on a V8 isolate that spins up in roughly a millisecond — near-zero cold starts.
For low-traffic or bursty routes (webhooks, auth checks, redirects), Edge avoids the "first request is slow" penalty that Node functions can suffer.
Geographic Latency
Node serverless functions usually run in one region (the region you deployed to). A user in Tokyo hitting a function in Virginia pays a full round-trip across the planet.
Edge functions are replicated globally and run at the location nearest the user. For latency-sensitive, compute-light work this dramatically cuts response time.
Caveat: if your Edge function then calls a database in a single far-away region, you've just moved the latency. Edge wins most when it needs little or no origin data, or talks to a globally distributed data store.
What Edge Can't Do
The Edge runtime exposes only Web standard APIs (fetch, Request, Response, crypto.subtle, TextEncoder, ...). It does not include Node built-ins.
- No
fs, nonet, no raw TCP sockets. - Native/C++ addon packages won't run.
- Many database drivers that use TCP (the default
pg,mysql2) won't work directly.
If a route imports a library that needs these, keep it on Node.
// This FAILS on the Edge runtime:
// import fs from 'node:fs'; // 'fs' is not available
// import { Pool } from 'pg'; // raw TCP socket not supported
// Edge-friendly work uses Web APIs only:
export const runtime = 'edge';
export async function GET() {
const data = await fetch('https://api.example.com/feed').then(r => r.json());
return Response.json(data);
}Databases on the Edge
Because Edge can't open raw TCP connections, you reach databases over HTTP-based drivers instead.
- Neon serverless driver (
@neondatabase/serverless) — Postgres over HTTP/WebSocket. - Vercel Postgres / Turso (libSQL) / Upstash Redis — all HTTP-fetch based.
- Prisma with its Accelerate or a serverless adapter.
If your stack uses a classic pooled TCP connection, that route belongs on Node.
// app/api/count/route.ts
import { neon } from '@neondatabase/serverless';
export const runtime = 'edge';
const sql = neon(process.env.DATABASE_URL!); // HTTP-based, Edge-safe
export async function GET() {
const rows = await sql`SELECT count(*) AS total FROM visits`;
return Response.json({ total: rows[0].total });
}Streaming and Long Work
Both runtimes can stream responses, but their execution limits differ.
- Edge is optimized for short, fast responses and streaming (great for proxying AI token streams). It has stricter limits on CPU time and bundle size.
- Node can run longer, heavier compute and large dependency trees, and supports background-friendly patterns better.
A route that crunches a big payload, generates a PDF, or runs a heavy library should stay on Node.
// Streaming a response works on either runtime
export const runtime = 'edge';
export async function GET() {
const stream = new ReadableStream({
start(controller) {
const enc = new TextEncoder();
controller.enqueue(enc.encode('chunk-1\n'));
controller.enqueue(enc.encode('chunk-2\n'));
controller.close();
},
});
return new Response(stream, { headers: { 'Content-Type': 'text/plain' } });
}A Pure-Web Snippet You Can Run
Edge code sticks to Web APIs, which means the core logic is plain TypeScript that runs anywhere. Here's a standalone example using crypto.subtle and TextEncoder — exactly the kind of code that's Edge-safe because it needs no Node built-ins.
// Standalone: hash a string using only Web Crypto APIs
async function sha256Hex(input: string): Promise<string> {
const data = new TextEncoder().encode(input);
const digest = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
async function main() {
const hash = await sha256Hex('edge-runtime');
console.log(hash);
}
main();A Decision Helper
Sometimes it helps to encode the tradeoff as a simple rule. The function below returns a runtime recommendation from a few facts about a route. This is just plain TypeScript logic you can reason about and run.
type RouteNeeds = {
usesNodeApis: boolean; // fs, net, native addons
usesTcpDatabase: boolean; // classic pg/mysql driver
latencySensitive: boolean; // users worldwide, light compute
heavyCompute: boolean; // big payloads, PDF, large deps
};
function recommendRuntime(r: RouteNeeds): 'node' | 'edge' {
if (r.usesNodeApis || r.usesTcpDatabase || r.heavyCompute) return 'node';
if (r.latencySensitive) return 'edge';
return 'node';
}
console.log(recommendRuntime({ usesNodeApis: false, usesTcpDatabase: false, latencySensitive: true, heavyCompute: false }));
console.log(recommendRuntime({ usesNodeApis: false, usesTcpDatabase: true, latencySensitive: true, heavyCompute: false }));Mixing Runtimes in One App
The big win of per-route runtimes is that you can mix them. A typical Next.js 15 app might keep:
- Auth/session checks, redirects, A/B flags, lightweight proxies → Edge.
- Database writes via Prisma, file processing, third-party SDKs → Node.
Note: Server Actions run on the Node.js runtime in the App Router — the Edge opt-in shown here applies to Route Handlers and Middleware, not to Server Actions.
// app/api/flag/route.ts -> Edge: fast, global, no DB
export const runtime = 'edge';
export async function GET(req: Request) {
const country = req.headers.get('x-vercel-ip-country') ?? 'US';
return Response.json({ promoEnabled: country === 'US' });
}Reading Edge Geo Context
Edge runs near the user, so it's the natural place for geo-aware logic. On Vercel, geo data arrives as request headers (x-vercel-ip-country, x-vercel-ip-city). You can localize content or redirect without a round-trip to a central server.
If you needed a database lookup for every request, the Edge advantage shrinks — so reserve Edge for cases where the decision is cheap and data is local or cached.
// app/api/welcome/route.ts
export const runtime = 'edge';
export async function GET(req: Request) {
const country = req.headers.get('x-vercel-ip-country') ?? 'unknown';
const greeting = country === 'FR' ? 'Bonjour' : 'Hello';
return Response.json({ greeting, country });
}Quick Check
Pick the route most appropriate for the Edge runtime.
Recap: Choosing Per Route
You now choose the runtime per route based on real tradeoffs:
- Edge — near-zero cold starts, global low latency, Web APIs only. Best for lightweight, geo-aware, data-light routes (flags, redirects, auth checks, stream proxies).
- Node (default) — full Node APIs, npm packages, TCP databases, heavy compute and large dependencies.
Decide with concrete questions: Does it need Node APIs or a TCP DB driver? Is it heavy compute? If yes → Node. Is it light and latency-sensitive worldwide? → Edge. And remember: Server Actions run on Node; the runtime = 'edge' opt-in is for Route Handlers and Middleware.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 22
- บทเรียน
- 88
คำถามที่พบบ่อย
บทเรียน “ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack (App Router + Server Actions) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge”
เลือก Node หรือ Edge ต่อเส้นทางตามเวลาการเริ่มทำงานเมื่อแคชว่าง API ที่ใช้ได้ และเวลาแฝงตามภูมิศาสตร์ คุณปฏิบัติ Next.js 15 Fullstack (App Router + Server Actions) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack (App Router + Server Actions) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack (App Router + Server Actions) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack (App Router + Server Actions) นี้ได้ไหม
ได้ บทเรียน Next.js 15 Fullstack (App Router + Server Actions) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การออกแบบตัวจัดการเส้นทางแบบ RESTful ด้วย Web Request API
- ข้อแลกเปลี่ยนระหว่างรันไทม์ Node กับ Edge
- การตอบกลับแบบสตรีมและ ReadableStream ในตัวจัดการ
- การตรวจสอบคำขอและการตอบกลับ JSON แบบระบุชนิดด้วย Zod