Advanced Next.js middleware patterns for authentication, rate limiting, and request processing
# Next.js Middleware Patterns for Google Antigravity
Master Next.js middleware with Google Antigravity's Gemini 3 engine. This guide covers authentication, rate limiting, geolocation, A/B testing, and request rewriting patterns.
## Comprehensive Middleware Setup
```typescript
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyToken } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
// Routes that require authentication
const protectedRoutes = ['/dashboard', '/settings', '/api/user'];
// Routes that should redirect if already authenticated
const authRoutes = ['/login', '/signup'];
// API routes that need rate limiting
const rateLimitedRoutes = ['/api/'];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Apply rate limiting to API routes
if (rateLimitedRoutes.some(route => pathname.startsWith(route))) {
const rateLimitResult = await applyRateLimit(request);
if (rateLimitResult) return rateLimitResult;
}
// Handle authentication
const authResult = await handleAuth(request, pathname);
if (authResult) return authResult;
// Apply geolocation-based routing
const geoResult = handleGeolocation(request);
if (geoResult) return geoResult;
// Apply A/B testing
const abTestResult = handleABTest(request);
if (abTestResult) return abTestResult;
return NextResponse.next();
}
async function handleAuth(request: NextRequest, pathname: string) {
const token = request.cookies.get('auth-token')?.value;
const isAuthenticated = token ? await verifyToken(token) : false;
// Redirect to login if accessing protected route without auth
if (protectedRoutes.some(route => pathname.startsWith(route))) {
if (!isAuthenticated) {
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('redirect', pathname);
return NextResponse.redirect(loginUrl);
}
}
// Redirect to dashboard if accessing auth routes while authenticated
if (authRoutes.some(route => pathname.startsWith(route))) {
if (isAuthenticated) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
}
return null;
}
async function applyRateLimit(request: NextRequest) {
const ip = request.ip ?? request.headers.get('x-forwarded-for') ?? 'anonymous';
const { success, remaining, reset } = await rateLimit(ip);
if (!success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: {
'X-RateLimit-Remaining': remaining.toString(),
'X-RateLimit-Reset': reset.toString(),
'Retry-After': Math.ceil((reset - Date.now()) / 1000).toString(),
},
}
);
}
return null;
}
function handleGeolocation(request: NextRequest) {
const country = request.geo?.country;
// Redirect EU users to EU-specific content
const euCountries = ['DE', 'FR', 'IT', 'ES', 'NL', 'BE', 'AT', 'PL'];
if (country && euCountries.includes(country)) {
const pathname = request.nextUrl.pathname;
if (!pathname.startsWith('/eu') && pathname === '/') {
return NextResponse.rewrite(new URL('/eu', request.url));
}
}
return null;
}
function handleABTest(request: NextRequest) {
const abTestCookie = request.cookies.get('ab-test-variant');
let variant = abTestCookie?.value;
if (!variant) {
variant = Math.random() < 0.5 ? 'control' : 'experiment';
const response = NextResponse.next();
response.cookies.set('ab-test-variant', variant, {
maxAge: 60 * 60 * 24 * 30,
httpOnly: true,
});
return response;
}
return null;
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|public/).*)',
],
};
```
## Rate Limiter Implementation
```typescript
// lib/rate-limit.ts
import { Redis } from '@upstash/redis';
const redis = new Redis({
url: process.env.UPSTASH_REDIS_URL!,
token: process.env.UPSTASH_REDIS_TOKEN!,
});
interface RateLimitResult {
success: boolean;
remaining: number;
reset: number;
}
const WINDOW_SIZE = 60 * 1000; // 1 minute
const MAX_REQUESTS = 100;
export async function rateLimit(identifier: string): Promise<RateLimitResult> {
const now = Date.now();
const windowStart = now - WINDOW_SIZE;
const key = `rate_limit:${identifier}`;
// Remove old entries and count recent requests
const pipeline = redis.pipeline();
pipeline.zremrangebyscore(key, 0, windowStart);
pipeline.zadd(key, { score: now, member: `${now}-${Math.random()}` });
pipeline.zcard(key);
pipeline.expire(key, 60);
const results = await pipeline.exec();
const requestCount = results[2] as number;
const success = requestCount <= MAX_REQUESTS;
const remaining = Math.max(0, MAX_REQUESTS - requestCount);
const reset = now + WINDOW_SIZE;
return { success, remaining, reset };
}
```
## Request Headers and Cookies
```typescript
// lib/middleware-utils.ts
import { NextRequest, NextResponse } from 'next/server';
export function setSecurityHeaders(response: NextResponse): NextResponse {
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
response.headers.set(
'Permissions-Policy',
'camera=(), microphone=(), geolocation=()'
);
return response;
}
export function addRequestId(request: NextRequest): NextResponse {
const requestId = crypto.randomUUID();
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-request-id', requestId);
const response = NextResponse.next({
request: { headers: requestHeaders },
});
response.headers.set('x-request-id', requestId);
return response;
}
export function parseUserAgent(request: NextRequest) {
const userAgent = request.headers.get('user-agent') ?? '';
return {
isMobile: /mobile/i.test(userAgent),
isBot: /bot|crawler|spider/i.test(userAgent),
browser: userAgent.match(/(chrome|safari|firefox|edge)/i)?.[1] ?? 'unknown',
};
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these middleware patterns: Keep middleware lightweight to avoid latency. Use Edge Runtime for global low-latency execution. Implement proper error handling with fallbacks. Cache expensive operations like token verification. Use the matcher config to skip static assets for better performance.This Next.js 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 next.js 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 Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.