Implement powerful middleware for authentication and more
# Next.js Middleware Complete Guide for Google Antigravity
Build powerful middleware for edge computing with Next.js using Google Antigravity IDE.
## Authentication Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifyToken } from "./lib/auth";
const publicPaths = ["/", "/login", "/signup", "/api/auth"];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (publicPaths.some(path => pathname.startsWith(path))) {
return NextResponse.next();
}
const token = request.cookies.get("auth-token")?.value ||
request.headers.get("authorization")?.replace("Bearer ", "");
if (!token) {
if (pathname.startsWith("/api")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("redirect", pathname);
return NextResponse.redirect(loginUrl);
}
try {
const payload = await verifyToken(token);
const response = NextResponse.next();
response.headers.set("x-user-id", payload.sub);
response.headers.set("x-user-role", payload.role);
return response;
} catch (error) {
const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.delete("auth-token");
return response;
}
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"]
};
```
## Rate Limiting Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_URL!,
token: process.env.UPSTASH_REDIS_TOKEN!
});
const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, "10 s"),
analytics: true
});
export async function middleware(request: NextRequest) {
if (!request.nextUrl.pathname.startsWith("/api")) {
return NextResponse.next();
}
const ip = request.ip ?? request.headers.get("x-forwarded-for") ?? "anonymous";
const { success, limit, reset, remaining } = await ratelimit.limit(ip);
const response = success
? NextResponse.next()
: NextResponse.json({ error: "Too many requests" }, { status: 429 });
response.headers.set("X-RateLimit-Limit", limit.toString());
response.headers.set("X-RateLimit-Remaining", remaining.toString());
response.headers.set("X-RateLimit-Reset", reset.toString());
return response;
}
```
## Best Practices
1. **Keep middleware lightweight** for fast execution
2. **Use edge-compatible libraries** only
3. **Implement proper caching** for rate limiting
4. **Add comprehensive logging** for debugging
5. **Handle errors gracefully** with fallbacks
6. **Test with different scenarios** thoroughly
7. **Monitor performance** at the edge
Google Antigravity helps implement efficient middleware patterns with proper error handling.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.