Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Edge Runtime Middleware Patterns

Edge Runtime Middleware Patterns

Implement secure edge middleware in Next.js with Google Antigravity including authentication geolocation and A/B testing

MiddlewareEdgeNext.jsAuthenticationPerformance
by Antigravity Team
⭐0Stars
.antigravity
# 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 fallbacks

When to Use This Prompt

This Middleware prompt is ideal for developers working on:

  • Middleware applications requiring modern best practices and optimal performance
  • Projects that need production-ready Middleware code with proper error handling
  • Teams looking to standardize their middleware development workflow
  • Developers wanting to learn industry-standard Middleware patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Middleware code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Middleware prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...