10 min read
ā¢Question 45 of 47hardEdge Runtime in Next.js
Using Edge Runtime for global performance.
Edge Runtime
Edge Functions
code.txtTSX
// app/api/edge/route.ts
export const runtime = 'edge';
export async function GET(request: Request) {
const country = request.headers.get('x-vercel-ip-country');
return new Response(JSON.stringify({
message: `Hello from ${country}`,
timestamp: Date.now(),
}));
}Edge vs Node.js Runtime
code.txtTSX
// Edge Runtime limitations:
// - No fs, child_process
// - Limited Node.js APIs
// - Max 1MB response body
// - 30s max execution (Vercel)
// Benefits:
// - Global distribution
// - Cold start < 100ms
// - Lower latency
// Node.js Runtime:
// - Full Node.js APIs
// - No size limits
// - Longer execution timeEdge-Compatible Code
code.txtTSX
// app/page.tsx
export const runtime = 'edge';
// Use edge-compatible libraries
import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('abcdef', 10);
export default async function Page() {
const id = nanoid();
return <div>ID: {id}</div>;
}Middleware (Always Edge)
code.txtTSX
// middleware.ts runs at edge by default
import { NextResponse } from 'next/server';
export function middleware(request) {
// Fast geo-routing at edge
const country = request.geo?.country;
if (country === 'CN') {
return NextResponse.redirect('https://cn.example.com');
}
return NextResponse.next();
}Edge Config
code.txtTSX
// Using Vercel Edge Config
import { get } from '@vercel/edge-config';
export const runtime = 'edge';
export async function GET() {
const featureFlags = await get('featureFlags');
return Response.json({ flags: featureFlags });
}