Cursor rules for building robust API routes in Next.js with validation, error handling, and authentication.
.cursorrules in your project rootYou are an expert in building APIs with Next.js App Router.
## API Route Structure
```typescript
// app/api/posts/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
// Validation schema
const createPostSchema = z.object({
title: z.string().min(1).max(200),
content: z.string().min(1),
published: z.boolean().default(false),
});
export async function POST(request: NextRequest) {
try {
// 1. Authentication
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// 2. Parse and validate body
const body = await request.json();
const validatedData = createPostSchema.parse(body);
// 3. Business logic
const post = await prisma.post.create({
data: {
...validatedData,
authorId: session.user.id,
},
});
// 4. Return response
return NextResponse.json({ post }, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Validation failed', details: error.errors },
{ status: 400 }
);
}
console.error('POST /api/posts error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
## Dynamic API Routes
```typescript
// app/api/posts/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
interface RouteParams {
params: { id: string };
}
export async function GET(request: NextRequest, { params }: RouteParams) {
const { id } = params;
const post = await prisma.post.findUnique({
where: { id },
include: { author: true },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
return NextResponse.json({ post });
}
export async function PATCH(request: NextRequest, { params }: RouteParams) {
// Update logic
}
export async function DELETE(request: NextRequest, { params }: RouteParams) {
// Delete logic
}
```
## Response Helpers
```typescript
// lib/api-response.ts
export function successResponse<T>(data: T, status = 200) {
return NextResponse.json({ success: true, data }, { status });
}
export function errorResponse(message: string, status = 400) {
return NextResponse.json({ success: false, error: message }, { status });
}
export function paginatedResponse<T>(
data: T[],
page: number,
total: number,
limit: number
) {
return NextResponse.json({
success: true,
data,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
},
});
}
```Comprehensive Cursor rules for Next.js 14+ with App Router, including routing, layouts, and API patterns.
Cursor rules for TypeScript with strict type checking, advanced patterns, and best practices.
Cursor rules for Tailwind CSS development with responsive design, custom components, and dark mode.
Cursor
backend
AI coding rules customize how Cursor generates and refactors code for your project. Follow these steps to install Next.js API Development.
.cursor/rules, for Windsurf use .windsurfrulesComprehensive Cursor rules for Next.js 14+ with App Router, including routing, layouts, and API patterns.
Cursor rules for TypeScript with strict type checking, advanced patterns, and best practices.
Cursor rules for Tailwind CSS development with responsive design, custom components, and dark mode.