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 API Routes & REST APIs

Next.js API Routes & REST APIs

Build scalable REST APIs with Next.js API routes, including validation, error handling, and database integration.

Next.jsAPIRESTBackend
by Community
⭐0Stars
👁️9Views
.antigravity
# Next.js API Routes & REST APIs

Build robust REST APIs with Next.js App Router using Google Antigravity IDE. This comprehensive guide covers route handlers, middleware, validation, and API best practices.

## Why Next.js API Routes?

Next.js App Router provides a powerful API layer with edge and serverless support. Google Antigravity IDE's Gemini 3 engine helps you design scalable API architectures.

## Route Handler Setup

```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db } from "@/lib/db";
import { withAuth, withRateLimit } from "@/lib/middleware";

// Validation schemas
const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  password: z.string().min(8),
});

const querySchema = z.object({
  page: z.coerce.number().positive().default(1),
  limit: z.coerce.number().positive().max(100).default(20),
  search: z.string().optional(),
});

// GET /api/users
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const query = querySchema.parse({
      page: searchParams.get("page"),
      limit: searchParams.get("limit"),
      search: searchParams.get("search"),
    });
    
    const offset = (query.page - 1) * query.limit;
    
    const [users, total] = await Promise.all([
      db.user.findMany({
        where: query.search
          ? { name: { contains: query.search, mode: "insensitive" } }
          : undefined,
        skip: offset,
        take: query.limit,
        select: { id: true, email: true, name: true, createdAt: true },
      }),
      db.user.count(),
    ]);
    
    return NextResponse.json({
      data: users,
      pagination: {
        page: query.page,
        limit: query.limit,
        total,
        totalPages: Math.ceil(total / query.limit),
      },
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Invalid query parameters", details: error.errors },
        { status: 400 }
      );
    }
    throw error;
  }
}

// POST /api/users
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const data = createUserSchema.parse(body);
    
    // Check if email exists
    const existing = await db.user.findUnique({
      where: { email: data.email },
    });
    
    if (existing) {
      return NextResponse.json(
        { error: "Email already registered" },
        { status: 409 }
      );
    }
    
    // Hash password and create user
    const hashedPassword = await hashPassword(data.password);
    const user = await db.user.create({
      data: { ...data, password: hashedPassword },
      select: { id: true, email: true, name: true },
    });
    
    return NextResponse.json(user, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Validation failed", details: error.errors },
        { status: 400 }
      );
    }
    throw error;
  }
}
```

## Dynamic Route Handlers

```typescript
// app/api/users/[id]/route.ts
import { NextRequest, NextResponse } from "next/server";

interface RouteParams {
  params: { id: string };
}

// GET /api/users/:id
export async function GET(request: NextRequest, { params }: RouteParams) {
  const user = await db.user.findUnique({
    where: { id: params.id },
    select: { id: true, email: true, name: true, createdAt: true },
  });
  
  if (!user) {
    return NextResponse.json(
      { error: "User not found" },
      { status: 404 }
    );
  }
  
  return NextResponse.json(user);
}

// PATCH /api/users/:id
export async function PATCH(request: NextRequest, { params }: RouteParams) {
  const body = await request.json();
  const data = updateUserSchema.parse(body);
  
  const user = await db.user.update({
    where: { id: params.id },
    data,
    select: { id: true, email: true, name: true },
  });
  
  return NextResponse.json(user);
}

// DELETE /api/users/:id
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  await db.user.delete({ where: { id: params.id } });
  return new NextResponse(null, { status: 204 });
}
```

## API Middleware

```typescript
// lib/middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { verifyToken } from "./auth";
import { rateLimit } from "./rateLimit";

type Handler = (
  request: NextRequest,
  context: { params: Record<string, string> }
) => Promise<NextResponse>;

export function withAuth(handler: Handler): Handler {
  return async (request, context) => {
    const token = request.headers.get("authorization")?.replace("Bearer ", "");
    
    if (!token) {
      return NextResponse.json(
        { error: "Authentication required" },
        { status: 401 }
      );
    }
    
    try {
      const user = await verifyToken(token);
      request.headers.set("x-user-id", user.id);
      return handler(request, context);
    } catch {
      return NextResponse.json(
        { error: "Invalid token" },
        { status: 401 }
      );
    }
  };
}

export function withRateLimit(limit: number, window: number) {
  return (handler: Handler): Handler => {
    return async (request, context) => {
      const ip = request.ip ?? "anonymous";
      const { success, remaining } = await rateLimit(ip, limit, window);
      
      if (!success) {
        return NextResponse.json(
          { error: "Rate limit exceeded" },
          { status: 429, headers: { "Retry-After": String(window) } }
        );
      }
      
      const response = await handler(request, context);
      response.headers.set("X-RateLimit-Remaining", String(remaining));
      return response;
    };
  };
}
```

## Error Handling

```typescript
// lib/errorHandler.ts
export class APIError extends Error {
  constructor(
    public statusCode: number,
    message: string,
    public code?: string
  ) {
    super(message);
  }
}

export function handleError(error: unknown): NextResponse {
  if (error instanceof APIError) {
    return NextResponse.json(
      { error: error.message, code: error.code },
      { status: error.statusCode }
    );
  }
  
  console.error("Unhandled error:", error);
  return NextResponse.json(
    { error: "Internal server error" },
    { status: 500 }
  );
}
```

## Best Practices

- Use Zod for request validation
- Implement proper error handling
- Apply rate limiting for public APIs
- Use middleware for authentication
- Return appropriate HTTP status codes
- Document APIs with OpenAPI/Swagger

Google Antigravity IDE provides API route templates and automatically suggests security improvements for your Next.js REST APIs.

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