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
Next.js Middleware Patterns

Next.js Middleware Patterns

Advanced Next.js middleware patterns for authentication, rate limiting, and request processing

Next.jsMiddlewareAuthenticationPerformance
by Antigravity Team
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This Next.js prompt is ideal for developers working on:

  • Next.js applications requiring modern best practices and optimal performance
  • Projects that need production-ready Next.js code with proper error handling
  • Teams looking to standardize their next.js development workflow
  • Developers wanting to learn industry-standard Next.js 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 next.js 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 Next.js 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 Next.js 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 Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...