Next.js Functions คืออะไร? ทำไมจึงสำคัญ?
วันนี้ ทีม Vercel ประกาศ Next.js Edge Functions Edge Functions ให้นักพัฒนารันโค้ดที่ Servers ที่กระจายตัวทั่วโลก (Globally Distributed) หมายความว่าโค้ดของคุณจะ Execute ที่ Location ใกล้ User สุด คุณคิดว่า Edge Functions คือ Serverless Functions ที่รันบน CDN Infrastructure
Edge Functions มีข้อดี:
- Global Low Latency: โค้ด Replicate ไปหลาย Global Locations (PoPs: Points of Presence) User ทุกที่รู้สึก Low Latency แต่ละ Client จะ Fetch Response จาก Nearest Server
- No Cold Start: Edge Infrastructure Providers ใช้ V8 Isolates กำจัด Cold Starts ทำให้ Startup เร็วกว่ามาก
เริ่มต้นกับ Next.js Functions
เราจะเขียน Next.js Edge Function แสดง Custom Greeting ขึ้นกับ Location ของ Client โหลด Greeting Message จาก Upstash Redis
1. สร้าง Next.js Application และติดตั้ง Upstash Redis
npx create-next-app@latest --typescript
cd nextjs-edge
npm install @upstash/redis
2. สร้าง Redis Database
สร้าง Global Database เพื่อ Edge Latency ต่ำสุดใน Upstash Console เชื่อมต่อ Database ด้วย redis-cli เพิ่ม Greeting Data:
global-promoted-chicken-30286.upstash.io:30286> set GB "Ey up?" OK
global-promoted-chicken-30286.upstash.io:30286> set US "Yo, what's up?" OK
global-promoted-chicken-30286.upstash.io:30286> set TR "Naber dostum?" OK
global-promoted-chicken-30286.upstash.io:30286> set DE "Was ist los?" OK
global-promoted-chicken-30286.upstash.io:30286> set IN "Namaste" OK
3. สร้าง Edge Function
สร้าง pages/api/_middleware.ts ดังนี้:
import type { NextFetchEvent, NextRequest } from "next/server";
import { Redis } from "@upstash/redis";
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
const country = req.geo.country || "US";
const redis = new Redis({
url: "UPSTASH_REDIS_REST_URL",
token: "UPSTASH_REDIS_REST_TOKEN",
});
const result = await redis.get<string>(country);
const greeting = result || "Hello World!";
return new Response(greeting);
}
Copy/Paste UPSTASH_REDIS_REST_URL และ UPSTASH_REDIS_REST_TOKEN จาก Database Page ใน Upstash Console
4. Run และ Deploy
รัน Local:
npm run dev
Check: https://localhost:3000/api/hello
คุณจะเห็น req.geo ไม่ได้ Define Deploy ไป Vercel เพื่อดูการทำงานบน Edge Infrastructure:
vercel deploy
Check: https://nextjs-edge-enesakar-upstash.vercel.app/api/hello
ทดสอบ Greeting จาก Location ต่างๆ ได้ด้วย VPN
สรุป
Next.js Edge เป็นข่าวดีสำหรับนักพัฒนาที่สร้าง Globally Fast Applications Upstash Redis เป็น Data Service ที่ออกแบบและ Optimize สำหรับ Edge Functions
Useful Links:
- Next.js Edge Functions Documentation: https://vercel.com/docs/concepts/functions/edge-functions
- Next.js Edge Examples: https://github.com/vercel/examples/tree/main/edge-functions