Master Next.js 15 middleware for authentication, geolocation, A/B testing, rate limiting, and request manipulation. Learn edge runtime patterns for high-performance request handling.
# Next.js 15 Middleware Advanced Patterns
Build powerful edge-based request handling with Next.js 15 middleware. Execute code before requests complete for authentication, redirects, headers, and more.
## Middleware Fundamentals
### Basic Setup and Matching
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export const config = {
matcher: [
// Match all paths except static files and api routes
"/((?!_next/static|_next/image|favicon.ico|public|api/webhooks).*)",
// Or be explicit about what to match
"/dashboard/:path*",
"/admin/:path*",
"/api/:path*",
],
};
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Add custom headers
response.headers.set("x-middleware-cache", "no-cache");
response.headers.set("x-request-id", crypto.randomUUID());
return response;
}
```
## Authentication Middleware
### JWT Token Validation
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtVerify } from "jose";
const SECRET = new TextEncoder().encode(process.env.JWT_SECRET);
async function verifyToken(token: string) {
try {
const { payload } = await jwtVerify(token, SECRET);
return payload;
} catch {
return null;
}
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Public routes
const publicRoutes = ["/", "/login", "/register", "/api/auth"];
if (publicRoutes.some((route) => pathname.startsWith(route))) {
return NextResponse.next();
}
// Check authentication
const token = request.cookies.get("auth-token")?.value;
if (!token) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
const payload = await verifyToken(token);
if (!payload) {
const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.delete("auth-token");
return response;
}
// Role-based access control
if (pathname.startsWith("/admin") && payload.role !== "admin") {
return NextResponse.redirect(new URL("/unauthorized", request.url));
}
// Add user info to headers for downstream use
const response = NextResponse.next();
response.headers.set("x-user-id", payload.sub as string);
response.headers.set("x-user-role", payload.role as string);
return response;
}
```
## Geolocation and Personalization
### Country-Based Routing
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const COUNTRY_LOCALES: Record<string, string> = {
US: "en-US",
GB: "en-GB",
DE: "de-DE",
FR: "fr-FR",
JP: "ja-JP",
CN: "zh-CN",
};
export function middleware(request: NextRequest) {
const country = request.geo?.country || "US";
const city = request.geo?.city || "Unknown";
const region = request.geo?.region || "Unknown";
// Redirect to country-specific subdomain
if (country === "CN" && !request.nextUrl.hostname.startsWith("cn.")) {
return NextResponse.redirect(
new URL(`https://cn.example.com${request.nextUrl.pathname}`)
);
}
// Set locale cookie based on country
const response = NextResponse.next();
const locale = COUNTRY_LOCALES[country] || "en-US";
if (!request.cookies.has("locale")) {
response.cookies.set("locale", locale, {
maxAge: 60 * 60 * 24 * 365,
path: "/",
});
}
// Add geo headers for server components
response.headers.set("x-geo-country", country);
response.headers.set("x-geo-city", city);
response.headers.set("x-geo-region", region);
return response;
}
```
## Rate Limiting
### Token Bucket Algorithm
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Simple in-memory store (use Redis in production)
const rateLimitStore = new Map<string, { tokens: number; lastRefill: number }>();
const RATE_LIMIT = {
tokensPerInterval: 100,
interval: 60 * 1000, // 1 minute
maxTokens: 100,
};
function getRateLimitKey(request: NextRequest): string {
const ip = request.ip || request.headers.get("x-forwarded-for") || "anonymous";
return `rate-limit:${ip}`;
}
function checkRateLimit(key: string): { allowed: boolean; remaining: number } {
const now = Date.now();
let bucket = rateLimitStore.get(key);
if (!bucket) {
bucket = { tokens: RATE_LIMIT.maxTokens, lastRefill: now };
rateLimitStore.set(key, bucket);
}
// Refill tokens
const timePassed = now - bucket.lastRefill;
const tokensToAdd = Math.floor(timePassed / RATE_LIMIT.interval) * RATE_LIMIT.tokensPerInterval;
bucket.tokens = Math.min(RATE_LIMIT.maxTokens, bucket.tokens + tokensToAdd);
bucket.lastRefill = now;
if (bucket.tokens > 0) {
bucket.tokens--;
return { allowed: true, remaining: bucket.tokens };
}
return { allowed: false, remaining: 0 };
}
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith("/api/")) {
const key = getRateLimitKey(request);
const { allowed, remaining } = checkRateLimit(key);
if (!allowed) {
return new NextResponse(JSON.stringify({ error: "Rate limit exceeded" }), {
status: 429,
headers: {
"Content-Type": "application/json",
"X-RateLimit-Remaining": "0",
"Retry-After": "60",
},
});
}
const response = NextResponse.next();
response.headers.set("X-RateLimit-Remaining", remaining.toString());
return response;
}
return NextResponse.next();
}
```
## A/B Testing
### Feature Flag Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
interface Experiment {
name: string;
variants: string[];
weights: number[];
}
const EXPERIMENTS: Experiment[] = [
{ name: "new-checkout", variants: ["control", "variant-a", "variant-b"], weights: [0.34, 0.33, 0.33] },
{ name: "pricing-page", variants: ["original", "simplified"], weights: [0.5, 0.5] },
];
function selectVariant(experiment: Experiment): string {
const random = Math.random();
let cumulative = 0;
for (let i = 0; i < experiment.variants.length; i++) {
cumulative += experiment.weights[i];
if (random < cumulative) {
return experiment.variants[i];
}
}
return experiment.variants[0];
}
export function middleware(request: NextRequest) {
const response = NextResponse.next();
for (const experiment of EXPERIMENTS) {
const cookieName = `exp-${experiment.name}`;
let variant = request.cookies.get(cookieName)?.value;
if (!variant) {
variant = selectVariant(experiment);
response.cookies.set(cookieName, variant, {
maxAge: 60 * 60 * 24 * 30, // 30 days
path: "/",
});
}
response.headers.set(`x-experiment-${experiment.name}`, variant);
}
return response;
}
```
## Security Headers
```typescript
// middleware.ts
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Security headers
response.headers.set("X-DNS-Prefetch-Control", "on");
response.headers.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains");
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("X-Frame-Options", "SAMEORIGIN");
response.headers.set("X-XSS-Protection", "1; mode=block");
response.headers.set("Referrer-Policy", "origin-when-cross-origin");
response.headers.set(
"Permissions-Policy",
"camera=(), microphone=(), geolocation=()"
);
return response;
}
```
This comprehensive middleware guide enables authentication, geolocation routing, rate limiting, A/B testing, and security hardening at the edge for optimal performance.This nextjs prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their nextjs implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For nextjs projects, consider mentioning your framework version, coding style, and any specific libraries you're using.