Build scalable REST APIs with Next.js API routes, including validation, error handling, and database integration.
# 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.This Next.js 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 next.js 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 Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.