DEV Community

Atlas Whoff
Atlas Whoff

Posted on

Vercel Edge Functions: Running Code at 40+ Locations Globally

Vercel Edge Functions: Running Code at 40+ Locations Globally

Normal serverless functions run in one region — a user in Tokyo hits your US-East function and waits 200ms before any work starts. Edge Functions run in 40+ locations globally, cutting that to 20ms.

What Are Edge Functions

Edge Functions run on V8 isolates (not Node.js) distributed worldwide. They start in ~0ms (no cold start), but have restrictions:

  • No Node.js APIs (no fs, crypto from Node, etc.)
  • Limited runtime: Web APIs only
  • 4 MB size limit
  • Max execution: 30 seconds

Next.js Middleware (Edge by default)

// middleware.ts — runs at the edge before every request
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // Geolocation — free, no API needed
  const country = request.geo?.country ?? 'US';
  const city = request.geo?.city ?? 'Unknown';

  // Redirect based on country
  if (country === 'GB') {
    return NextResponse.redirect(new URL('/uk', request.url));
  }

  // A/B testing at the edge
  const bucket = Math.random() < 0.5 ? 'a' : 'b';
  const response = NextResponse.next();
  response.cookies.set('ab-bucket', bucket);
  return response;
}

export const config = { matcher: '/((?!_next/static|_next/image|favicon.ico).*)' };
Enter fullscreen mode Exit fullscreen mode

Edge API Routes

// app/api/hello/route.ts
export const runtime = 'edge';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get('name') ?? 'World';

  return Response.json({
    message: `Hello, ${name}`,
    region: process.env.VERCEL_REGION,
  });
}
Enter fullscreen mode Exit fullscreen mode

Authentication at the Edge

// Validate JWT without hitting your database
import { jwtVerify } from 'jose';

export async function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value;

  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  try {
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);
    await jwtVerify(token, secret);
    return NextResponse.next();
  } catch {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
Enter fullscreen mode Exit fullscreen mode

Rate Limiting at the Edge

import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(100, '1 m'),
});

export async function middleware(request: NextRequest) {
  const ip = request.ip ?? '127.0.0.1';
  const { success } = await ratelimit.limit(ip);
  if (!success) return new Response('Too Many Requests', { status: 429 });
  return NextResponse.next();
}
Enter fullscreen mode Exit fullscreen mode

When NOT to Use Edge

  • Complex database queries (Prisma needs Node.js)
  • Heavy computation (CPU time limited)
  • File system operations
  • Anything needing Node.js-specific packages

Edge-optimized deployment is pre-configured in the AI SaaS Starter Kit — middleware for auth + rate limiting, Upstash Redis for edge-compatible caching. $99 at whoffagents.com.

Top comments (0)