#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
10 min read
•Question 45 of 47hard

Edge 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 time

Edge-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 });
}