Next.js Middleware & Edge Functions Cheat Sheet
What is Middleware?
- Code that runs before a request is completed.
- Runs at the edge (globally distributed, low latency).
- Use for: auth, redirects, rewrites, logging, headers, A/B testing.
Basic Middleware Example
// middleware.js (root or inside /app)
import { NextResponse } from "next/server";
export function middleware(request) {
// Example: Block access to /admin if not logged in
const isLoggedIn = Boolean(request.cookies.get("session"));
if (!isLoggedIn && request.nextUrl.pathname.startsWith("/admin")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
// Apply to all routes or use config.matcher
export const config = {
matcher: ["/admin/:path*"],
};
Common Use Cases
- Authentication/Authorization: Protect routes, check tokens/cookies.
- Redirects/Rewrites: Change destination or URL structure.
- Headers: Add security or custom headers.
- A/B Testing: Route users to different variants.
- Geo/Locale Handling: Redirect based on country/language.
Edge API Routes
- Place API files in
/pages/api
or/app/api
and exportruntime = "edge"
.
// app/api/hello/route.js
export const runtime = "edge";
export async function GET() {
return new Response(JSON.stringify({ message: "Hello from the edge!" }), {
headers: { "Content-Type": "application/json" },
});
}
Middleware Limitations
- No access to Node.js APIs (e.g., fs, net, process).
- Only Web APIs (Request, Response, URL, etc.).
- No database connections—use tokens/cookies for lightweight checks.
Best Practices
- Keep middleware fast and stateless.
- Use matchers to limit scope.
- Avoid heavy computation or blocking calls.
- Use for security, routing, and personalization at the edge.
This cheatsheet gives developers a quick reference for using middleware and edge functions in Next.js, with practical examples and best practices.