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 FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 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 & Authentication

Next.js Middleware & Authentication

Implement robust authentication and authorization using Next.js middleware with JWT, session management, and protected routes.

Next.jsAuthMiddlewareSecurity
by Community
⭐0Stars
👁️6Views
.antigravity
# Next.js Middleware & Authentication for Google Antigravity

Master Next.js middleware and authentication patterns in your Google Antigravity projects. This guide covers route protection, JWT validation, role-based access, and session management.

## Middleware Configuration

Create comprehensive authentication middleware:

```typescript
// middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { jwtVerify } from "jose";

// Route configuration
const PUBLIC_ROUTES = ["/", "/login", "/signup", "/forgot-password", "/reset-password"];
const AUTH_ROUTES = ["/login", "/signup"];
const API_AUTH_ROUTES = ["/api/auth/login", "/api/auth/signup", "/api/auth/refresh"];
const ADMIN_ROUTES = ["/admin", "/admin/users", "/admin/settings"];

// JWT verification
async function verifyToken(token: string): Promise<{ userId: string; role: string } | null> {
  try {
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);
    const { payload } = await jwtVerify(token, secret);
    
    return {
      userId: payload.userId as string,
      role: payload.role as string,
    };
  } catch {
    return null;
  }
}

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  
  // Skip middleware for static files and Next.js internals
  if (
    pathname.startsWith("/_next") ||
    pathname.startsWith("/static") ||
    pathname.includes(".") // Files with extensions
  ) {
    return NextResponse.next();
  }
  
  // Get tokens from cookies
  const accessToken = request.cookies.get("access_token")?.value;
  const refreshToken = request.cookies.get("refresh_token")?.value;
  
  // Verify access token
  let user = accessToken ? await verifyToken(accessToken) : null;
  
  // Try to refresh if access token is invalid
  if (!user && refreshToken) {
    try {
      const refreshResponse = await fetch(
        new URL("/api/auth/refresh", request.url),
        {
          method: "POST",
          headers: {
            Cookie: `refresh_token=${refreshToken}`,
          },
        }
      );
      
      if (refreshResponse.ok) {
        const data = await refreshResponse.json();
        user = await verifyToken(data.accessToken);
        
        // Create response with new tokens
        const response = NextResponse.next();
        
        response.cookies.set("access_token", data.accessToken, {
          httpOnly: true,
          secure: process.env.NODE_ENV === "production",
          sameSite: "lax",
          maxAge: 60 * 15, // 15 minutes
        });
        
        if (data.refreshToken) {
          response.cookies.set("refresh_token", data.refreshToken, {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            sameSite: "lax",
            maxAge: 60 * 60 * 24 * 7, // 7 days
          });
        }
        
        // Continue with the refreshed token
        return handleRouteAccess(request, user, response);
      }
    } catch {
      // Refresh failed, clear tokens
      const response = NextResponse.redirect(new URL("/login", request.url));
      response.cookies.delete("access_token");
      response.cookies.delete("refresh_token");
      return response;
    }
  }
  
  return handleRouteAccess(request, user);
}

function handleRouteAccess(
  request: NextRequest,
  user: { userId: string; role: string } | null,
  response?: NextResponse
): NextResponse {
  const { pathname } = request.nextUrl;
  const res = response || NextResponse.next();
  
  // Handle API routes
  if (pathname.startsWith("/api/")) {
    // Allow public API routes
    if (API_AUTH_ROUTES.some((route) => pathname.startsWith(route))) {
      return res;
    }
    
    // Require authentication for other API routes
    if (!user) {
      return NextResponse.json(
        { error: "Unauthorized" },
        { status: 401 }
      );
    }
    
    // Add user info to headers for API routes
    res.headers.set("x-user-id", user.userId);
    res.headers.set("x-user-role", user.role);
    
    return res;
  }
  
  // Redirect authenticated users away from auth pages
  if (user && AUTH_ROUTES.some((route) => pathname === route)) {
    return NextResponse.redirect(new URL("/dashboard", request.url));
  }
  
  // Allow public routes
  if (PUBLIC_ROUTES.some((route) => pathname === route)) {
    return res;
  }
  
  // Require authentication for protected routes
  if (!user) {
    const loginUrl = new URL("/login", request.url);
    loginUrl.searchParams.set("redirect", pathname);
    return NextResponse.redirect(loginUrl);
  }
  
  // Check admin access
  if (ADMIN_ROUTES.some((route) => pathname.startsWith(route))) {
    if (user.role !== "admin") {
      return NextResponse.redirect(new URL("/unauthorized", request.url));
    }
  }
  
  return res;
}

export const config = {
  matcher: [
    /*
     * Match all paths except:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - public folder
     */
    "/((?!_next/static|_next/image|favicon.ico|public/).*)",
  ],
};
```

## Authentication API Routes

Implement secure authentication endpoints:

```typescript
// src/app/api/auth/login/route.ts
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import bcrypt from "bcryptjs";
import { SignJWT } from "jose";
import { db } from "@/lib/database";

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
  rememberMe: z.boolean().optional(),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, password, rememberMe } = loginSchema.parse(body);
    
    // Find user
    const user = await db.user.findUnique({
      where: { email },
      select: {
        id: true,
        email: true,
        name: true,
        password: true,
        role: true,
        status: true,
      },
    });
    
    if (!user) {
      return NextResponse.json(
        { error: "Invalid credentials" },
        { status: 401 }
      );
    }
    
    // Check password
    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      return NextResponse.json(
        { error: "Invalid credentials" },
        { status: 401 }
      );
    }
    
    // Check account status
    if (user.status !== "active") {
      return NextResponse.json(
        { error: "Account is not active" },
        { status: 403 }
      );
    }
    
    // Generate tokens
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);
    
    const accessToken = await new SignJWT({
      userId: user.id,
      email: user.email,
      role: user.role,
    })
      .setProtectedHeader({ alg: "HS256" })
      .setIssuedAt()
      .setExpirationTime("15m")
      .sign(secret);
    
    const refreshToken = await new SignJWT({
      userId: user.id,
      type: "refresh",
    })
      .setProtectedHeader({ alg: "HS256" })
      .setIssuedAt()
      .setExpirationTime(rememberMe ? "30d" : "7d")
      .sign(secret);
    
    // Store refresh token in database
    await db.refreshToken.create({
      data: {
        token: refreshToken,
        userId: user.id,
        expiresAt: new Date(Date.now() + (rememberMe ? 30 : 7) * 24 * 60 * 60 * 1000),
      },
    });
    
    // Create response with cookies
    const response = NextResponse.json({
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role,
      },
    });
    
    response.cookies.set("access_token", accessToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 15,
    });
    
    response.cookies.set("refresh_token", refreshToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: (rememberMe ? 30 : 7) * 24 * 60 * 60,
    });
    
    return response;
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Validation failed", details: error.errors },
        { status: 400 }
      );
    }
    
    console.error("Login error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
```

## Protected Page Components

Create authentication-aware components:

```typescript
// src/components/auth/withAuth.tsx
"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";

interface WithAuthOptions {
  requiredRole?: "user" | "admin";
  redirectTo?: string;
}

export function withAuth<P extends object>(
  Component: React.ComponentType<P>,
  options: WithAuthOptions = {}
) {
  const { requiredRole, redirectTo = "/login" } = options;
  
  return function ProtectedComponent(props: P) {
    const router = useRouter();
    const { user, isLoading, isAuthenticated } = useAuth();
    
    useEffect(() => {
      if (!isLoading && !isAuthenticated) {
        router.push(`${redirectTo}?redirect=${window.location.pathname}`);
      }
      
      if (!isLoading && isAuthenticated && requiredRole) {
        if (user?.role !== requiredRole) {
          router.push("/unauthorized");
        }
      }
    }, [isLoading, isAuthenticated, user, router]);
    
    if (isLoading) {
      return (
        <div className="flex min-h-screen items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
        </div>
      );
    }
    
    if (!isAuthenticated) {
      return null;
    }
    
    if (requiredRole && user?.role !== requiredRole) {
      return null;
    }
    
    return <Component {...props} />;
  };
}

// Usage
const AdminDashboard = withAuth(DashboardComponent, { requiredRole: "admin" });
```

Google Antigravity generates comprehensive Next.js authentication with middleware protection, JWT handling, and role-based access control for secure applications.

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...