Implement secure edge middleware in Next.js with Google Antigravity including authentication geolocation and A/B testing
# Edge Runtime Middleware Patterns for Google Antigravity
Edge middleware runs before requests hit your server, enabling fast, globally distributed logic. This guide establishes patterns for building edge middleware with Google Antigravity.
## Authentication at the Edge
```typescript
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtVerify } from "jose";
const secret = new TextEncoder().encode(process.env.JWT_SECRET!);
export async function middleware(request: NextRequest) {
const token = request.cookies.get("token")?.value;
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
try {
const { payload } = await jwtVerify(token, secret);
const response = NextResponse.next();
response.headers.set("x-user-id", payload.sub as string);
return response;
} catch {
return NextResponse.redirect(new URL("/login", request.url));
}
}
export const config = {
matcher: ["/dashboard/:path*", "/api/protected/:path*"],
};
```
## Geolocation Routing
```typescript
export function middleware(request: NextRequest) {
const country = request.geo?.country || "US";
const city = request.geo?.city || "Unknown";
// Redirect EU users to EU-specific page
if (["DE", "FR", "IT", "ES", "NL"].includes(country)) {
if (!request.nextUrl.pathname.startsWith("/eu")) {
return NextResponse.redirect(new URL(`/eu${request.nextUrl.pathname}`, request.url));
}
}
const response = NextResponse.next();
response.headers.set("x-country", country);
response.headers.set("x-city", city);
return response;
}
```
## A/B Testing
```typescript
export function middleware(request: NextRequest) {
let bucket = request.cookies.get("ab-bucket")?.value;
if (!bucket) {
bucket = Math.random() < 0.5 ? "control" : "variant";
}
const response = bucket === "variant"
? NextResponse.rewrite(new URL("/home-variant", request.url))
: NextResponse.next();
response.cookies.set("ab-bucket", bucket, { maxAge: 60 * 60 * 24 * 30 });
return response;
}
```
## Rate Limiting
```typescript
const ipCounts = new Map<string, { count: number; reset: number }>();
export function middleware(request: NextRequest) {
const ip = request.ip || "unknown";
const now = Date.now();
const record = ipCounts.get(ip);
if (!record || now > record.reset) {
ipCounts.set(ip, { count: 1, reset: now + 60000 });
return NextResponse.next();
}
if (record.count >= 100) {
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
}
record.count++;
return NextResponse.next();
}
```
## Best Practices
1. **Edge-compatible code**: No Node.js APIs
2. **Fast execution**: Keep logic minimal
3. **Stateless**: Use cookies for state
4. **Global distribution**: Leverage CDN edge
5. **Error handling**: Always have fallbacksThis Middleware 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 middleware 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 Middleware projects, consider mentioning your framework version, coding style, and any specific libraries you're using.