Edge & Serverless Functions

Vercel provides two runtimes for server-side code: Edge Functions and Serverless Functions. Each has distinct performance characteristics and use cases.

Runtime Comparison

FeatureEdge FunctionsServerless Functions
Cold start~0ms250ms+
Execution limit30 seconds (streaming)60 seconds (Hobby) / 900s (Pro)
Max size4 MB250 MB
RuntimeV8 isolatesNode.js
RegionsAll edge locationsSelect regions
Node.js APIsSubset onlyFull access
NPM packagesLimitedFull support

When to Use Each

Use Edge Functions When:

  • You need the lowest possible latency globally
  • The logic is lightweight (auth checks, redirects, A/B tests)
  • You are transforming or personalizing responses
  • You do not need Node.js-specific APIs like fs or native modules

Use Serverless Functions When:

  • You need full Node.js compatibility
  • Your function depends on large NPM packages
  • You are doing database queries with Node.js drivers
  • The function performs heavy computation

Edge Middleware

Middleware runs before every request and is always deployed to the edge:

// middleware.ts (root of project)
import { NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  const token = request.cookies.get("session");

  if (!token && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/api/protected/:path*"],
};

Configuring the Runtime

Set the runtime for a Route Handler or page:

// app/api/fast/route.ts
export const runtime = "edge";

export async function GET() {
  return new Response(JSON.stringify({ time: Date.now() }), {
    headers: { "content-type": "application/json" },
  });
}
// app/api/heavy/route.ts
export const runtime = "nodejs"; // default

export async function GET() {
  // Full Node.js available here
  return Response.json({ status: "ok" });
}

Performance Considerations

  • Edge functions execute in the region closest to the user, reducing round-trip time
  • Serverless functions execute in a single region by default; configure preferredRegion to optimize placement near your database
// Run this serverless function near the US East database
export const preferredRegion = "iad1";

Region Selection Tips

Database LocationRecommended Region
AWS us-east-1iad1 (Washington, D.C.)
AWS eu-west-1dub1 (Dublin)
AWS ap-northeast-1hnd1 (Tokyo)

Start with the default Node.js runtime. Switch to Edge only when you have a clear latency requirement that benefits from running at the edge.