Lesson 6 of 10
Edge Functions & API Routes
Next.js Route Handlers replace the old pages/api directory. Edge Runtime functions run at the CDN edge - globally distributed, lower latency, but no Node.js APIs. Knowing when to use Node.js runtime vs Edge Runtime is a key architectural decision.
Route Handlers & Edge Runtime
// app/api/products/route.ts - REST API endpoint
import { NextRequest, NextResponse } from 'next/server';
export const runtime = 'edge'; // run at CDN edge, globally distributed
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const category = searchParams.get('category') ?? 'all';
// Edge functions can: fetch from external APIs, read headers/cookies, use Web Crypto
// Edge functions CANNOT: use Node.js-specific APIs (fs, crypto from 'node:crypto', etc.)
const products = await fetch(`https://api.example.com/products?category=${category}`, {
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
}).then(r => r.json());
return NextResponse.json(products, {
headers: {
'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=600',
},
});
}
export async function POST(request: NextRequest) {
const body = await request.json();
// Parse and validate with Zod
const result = productSchema.safeParse(body);
if (!result.success) {
return NextResponse.json({ error: result.error.flatten() }, { status: 422 });
}
const product = await createProduct(result.data);
return NextResponse.json(product, { status: 201 });
}
// Middleware - runs before every request, on the Edge
// middleware.ts (at root)
import { NextResponse, type NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Protected routes - check auth cookie
if (pathname.startsWith('/dashboard')) {
const token = request.cookies.get('access_token')?.value;
if (!token || !isValidToken(token)) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
// A/B testing - set variant cookie
if (pathname === '/pricing' && !request.cookies.has('pricing_variant')) {
const response = NextResponse.next();
response.cookies.set('pricing_variant', Math.random() < 0.5 ? 'A' : 'B');
return response;
}
// Geolocation-based routing
const country = request.geo?.country;
if (country === 'DE' && !pathname.startsWith('/de')) {
return NextResponse.redirect(new URL('/de' + pathname, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};Tip
Tip
Practice Edge Functions API Routes in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Edge Functions & API Routes
Practice Task
Note
Practice Task - (1) Write a working example of Edge Functions API Routes from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Edge Functions API Routes is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?