Edge Middleware
Overview
Middleware runs on the Edge runtime before a request reaches your page or API. It's used to inspect requests and perform redirects, rewrites, or set cookies globally (like checking auth tokens before allowing access to a dashboard).
Syntax
// middleware.ts (in root directory, alongside app/)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('auth_token');
// If trying to access dashboard without a token, redirect to login
if (request.nextUrl.pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
// Only run middleware on specific paths
export const config = {
matcher: ['/dashboard/:path*'],
};Common Pitfalls
Using Node.js specific modules (like
fsorcrypto) inside middleware. Middleware runs on the Edge runtime, which only supports standard Web APIs.Omitting the
matcherconfig, causing the middleware to run on EVERY request (including images and CSS), which slows down the app.
Interview Questions
What is the primary difference between the Edge runtime and Node.js runtime?
Edge runtime is a lightweight, V8-based environment globally distributed close to users. It starts up instantly but lacks access to native Node APIs like file system access.
Real-World Example
A/B testing via Middleware.
export function middleware(req: NextRequest) {
const bucket = Math.random() < 0.5 ? 'a' : 'b';
req.nextUrl.pathname = `/marketing/${bucket}`;
return NextResponse.rewrite(req.nextUrl);
}Check Your Knowledge
Test your understanding of Edge Middleware with these quick questions.