Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.
.cursor/rules/nextjs-api-development.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape."
globs: "**/*"
alwaysApply: false
---
# Next.js API Development
Applies to: Route Handlers (`app/**/route.ts`) that serve JSON to external clients, mobile apps or webhooks in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 Route Handler reference and Zod 4. Read `package.json` first: on Next.js 14 `params` is a plain object; on Zod 3 use `error.errors` and `z.string().email()`.
Prefer Server Components for reads and Server Actions for the app's own forms. Use Route Handlers when something outside your React tree calls the endpoint.
## Handler contract
Every handler follows the same order:
1. Authenticate (unless the endpoint is intentionally public) and authorize the specific resource.
2. Parse and validate input with `safeParse`; reject with 400 and the issues.
3. Run business logic through a server-only data module.
4. Return a consistent JSON shape and an explicit status code.
5. Catch only what you can map to a status; log unexpected errors with the request path and return a generic 500.
## Response helpers
```ts
// lib/api-response.ts
import { NextResponse } from 'next/server'
import type { z } from 'zod'
export function ok<T>(data: T, status = 200) {
return NextResponse.json({ data }, { status })
}
export function fail(status: number, message: string, issues?: z.core.$ZodIssue[]) {
return NextResponse.json({ error: { message, issues } }, { status })
}
```
## Collection endpoint
```ts
// app/api/posts/route.ts
import type { NextRequest } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/session'
import { db } from '@/lib/db'
import { ok, fail } from '@/lib/api-response'
const createPost = z.object({
title: z.string().trim().min(1).max(200),
content: z.string().min(1),
published: z.boolean().default(false),
})
const listQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
})
export async function GET(request: NextRequest) {
const query = listQuery.safeParse(Object.fromEntries(request.nextUrl.searchParams))
if (!query.success) return fail(400, 'Invalid query', query.error.issues)
const { page, limit } = query.data
const [posts, total] = await Promise.all([
db.post.findMany({ where: { published: true }, skip: (page - 1) * limit, take: limit }),
db.post.count({ where: { published: true } }),
])
return ok({ posts, page, limit, total, totalPages: Math.ceil(total / limit) })
}
export async function POST(request: NextRequest) {
const session = await getSession()
if (!session) return fail(401, 'Unauthorized')
const body = createPost.safeParse(await request.json().catch(() => null))
if (!body.success) return fail(400, 'Validation failed', body.error.issues)
const post = await db.post.create({ data: { ...body.data, authorId: session.userId } })
return ok(post, 201)
}
```
`getSession` stands for the project's own auth helper (Auth.js `auth()`, Better Auth, a custom session); use whatever the project already has.
## Dynamic segment
`params` is a Promise. Check ownership before updating or deleting.
```ts
// app/api/posts/[id]/route.ts
import type { NextRequest } from 'next/server'
import { getSession } from '@/lib/session'
import { db } from '@/lib/db'
import { ok, fail } from '@/lib/api-response'
type Context = { params: Promise<{ id: string }> }
export async function GET(_request: NextRequest, { params }: Context) {
const { id } = await params
const post = await db.post.findUnique({ where: { id } })
return post ? ok(post) : fail(404, 'Post not found')
}
export async function DELETE(_request: NextRequest, { params }: Context) {
const session = await getSession()
if (!session) return fail(401, 'Unauthorized')
const { id } = await params
const post = await db.post.findUnique({ where: { id } })
if (!post) return fail(404, 'Post not found')
if (post.authorId !== session.userId && session.role !== 'ADMIN') return fail(403, 'Forbidden')
await db.post.delete({ where: { id } })
return new Response(null, { status: 204 })
}
```
After route types are generated (`next typegen`, `next dev` or `next build`), `RouteContext<'/api/posts/[id]'>` can replace the hand-written `Context` type.
## Other rules
- Never spread an unvalidated body into a database call; mass assignment lets clients set fields such as `authorId` or `role`.
- Bound pagination (`max(100)`) and prefer cursor pagination for large, frequently changing tables.
- `GET` handlers are not cached by default; opt into caching deliberately.
- For webhooks, verify the provider's signature against the raw body (`await request.text()`) before parsing JSON.
- Add CORS headers only for the origins that need them, and handle `OPTIONS` explicitly when you do.
## Verify before finishing
- `npx tsc --noEmit` passes.
- `curl` checks: unauthenticated `POST` returns 401; `{}` body returns 400 with `issues`; `?limit=1000` returns 400; another user's `DELETE` returns 403; success returns 201 or 204.
- Route Handler tests (if the project has them) call the exported functions with `new NextRequest(...)` and assert status and JSON.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Building a JSON posts API for a mobile client in a Next.js 16 project that already has a session helper.
Create GET/POST /api/posts and GET/DELETE /api/posts/[id]. Only the author or an ADMIN may delete. Use getSession() from lib/session.ts (returns { userId, role } or null) and db from lib/db.ts. Cap page size at 100.Illustrative; not a recorded model run. ok()/fail() helpers returning { data } or { error: { message, issues } }; Zod 4 schemas with z.coerce for query params and .max(100); POST returning 401 without a session, 400 with issues for invalid or non-JSON bodies, 201 on success with authorId from the session (not the body); [id] handlers typed with params: Promise<{ id: string }>; DELETE returning 404, 403 for non-owners, 204 on success.Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/nextjs-api-development.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Next.js API Development: Validated Route Handlers with Auth and Consistent Errors project conventions"
globs: "**/*"
alwaysApply: false
---
# Next.js API Development
Applies to: Route Handlers (`app/**/route.ts`) that serve JSON to external clients, mobile apps or webhooks in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 Route Handler reference and Zod 4. Read `package.json` first: on Next.js 14 `params` is a plain object; on Zod 3 use `error.errors` and `z.string().email()`.
Prefer Server Components for reads and Server Actions for the app's own forms. Use Route Handlers when something outside your React tree calls the endpoint.
## Handler contract
Every handler follows the same order:
1. Authenticate (unless the endpoint is intentionally public) and authorize the specific resource.
2. Parse and validate input with `safeParse`; reject with 400 and the issues.
3. Run business logic through a server-only data module.
4. Return a consistent JSON shape and an explicit status code.
5. Catch only what you can map to a status; log unexpected errors with the request path and return a generic 500.
## Response helpers
```ts
// lib/api-response.ts
import { NextResponse } from 'next/server'
import type { z } from 'zod'
export function ok<T>(data: T, status = 200) {
return NextResponse.json({ data }, { status })
}
export function fail(status: number, message: string, issues?: z.core.$ZodIssue[]) {
return NextResponse.json({ error: { message, issues } }, { status })
}
```
## Collection endpoint
```ts
// app/api/posts/route.ts
import type { NextRequest } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/session'
import { db } from '@/lib/db'
import { ok, fail } from '@/lib/api-response'
const createPost = z.object({
title: z.string().trim().min(1).max(200),
content: z.string().min(1),
published: z.boolean().default(false),
})
const listQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
})
export async function GET(request: NextRequest) {
const query = listQuery.safeParse(Object.fromEntries(request.nextUrl.searchParams))
if (!query.success) return fail(400, 'Invalid query', query.error.issues)
const { page, limit } = query.data
const [posts, total] = await Promise.all([
db.post.findMany({ where: { published: true }, skip: (page - 1) * limit, take: limit }),
db.post.count({ where: { published: true } }),
])
return ok({ posts, page, limit, total, totalPages: Math.ceil(total / limit) })
}
export async function POST(request: NextRequest) {
const session = await getSession()
if (!session) return fail(401, 'Unauthorized')
const body = createPost.safeParse(await request.json().catch(() => null))
if (!body.success) return fail(400, 'Validation failed', body.error.issues)
const post = await db.post.create({ data: { ...body.data, authorId: session.userId } })
return ok(post, 201)
}
```
`getSession` stands for the project's own auth helper (Auth.js `auth()`, Better Auth, a custom session); use whatever the project already has.
## Dynamic segment
`params` is a Promise. Check ownership before updating or deleting.
```ts
// app/api/posts/[id]/route.ts
import type { NextRequest } from 'next/server'
import { getSession } from '@/lib/session'
import { db } from '@/lib/db'
import { ok, fail } from '@/lib/api-response'
type Context = { params: Promise<{ id: string }> }
export async function GET(_request: NextRequest, { params }: Context) {
const { id } = await params
const post = await db.post.findUnique({ where: { id } })
return post ? ok(post) : fail(404, 'Post not found')
}
export async function DELETE(_request: NextRequest, { params }: Context) {
const session = await getSession()
if (!session) return fail(401, 'Unauthorized')
const { id } = await params
const post = await db.post.findUnique({ where: { id } })
if (!post) return fail(404, 'Post not found')
if (post.authorId !== session.userId && session.role !== 'ADMIN') return fail(403, 'Forbidden')
await db.post.delete({ where: { id } })
return new Response(null, { status: 204 })
}
```
After route types are generated (`next typegen`, `next dev` or `next build`), `RouteContext<'/api/posts/[id]'>` can replace the hand-written `Context` type.
## Other rules
- Never spread an unvalidated body into a database call; mass assignment lets clients set fields such as `authorId` or `role`.
- Bound pagination (`max(100)`) and prefer cursor pagination for large, frequently changing tables.
- `GET` handlers are not cached by default; opt into caching deliberately.
- For webhooks, verify the provider's signature against the raw body (`await request.text()`) before parsing JSON.
- Add CORS headers only for the origins that need them, and handle `OPTIONS` explicitly when you do.
## Verify before finishing
- `npx tsc --noEmit` passes.
- `curl` checks: unauthenticated `POST` returns 401; `{}` body returns 400 with `issues`; `?limit=1000` returns 400; another user's `DELETE` returns 403; success returns 201 or 204.
- Route Handler tests (if the project has them) call the exported functions with `new NextRequest(...)` and assert status and JSON.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.