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/nextjs-14-app-router-complete-guide.mdc. Downloaded files need to be placed in that repository path.---
description: "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."
globs: "**/*"
alwaysApply: false
---
# Next.js App Router Guide (Next.js 14+, updated for Next.js 16)
Applies to: day-to-day work in a Next.js App Router project: project layout, routing files, Route Handlers, metadata and request interception.
Version baseline: originally written for Next.js 14; checked against the Next.js 16.3 documentation. Read `package.json` before writing code and apply the version notes below:
- Next.js 15+: `params`, `searchParams`, `cookies()` and `headers()` are async. Await them.
- Next.js 16: `middleware.ts` is deprecated and renamed `proxy.ts` (export `proxy`); `fetch` is not cached by default, and the Cache Components model (`'use cache'`) replaces `unstable_cache`.
- On Next.js 14, keep synchronous `params` and `middleware.ts`.
## Project structure
```
app/
├── (auth)/ # Route group (no URL segment)
│ ├── login/page.tsx # /login
│ └── signup/page.tsx # /signup
├── (dashboard)/
│ ├── layout.tsx # Shared dashboard layout
│ └── dashboard/
│ ├── page.tsx # /dashboard
│ └── settings/page.tsx # /dashboard/settings
├── api/users/route.ts # Route Handler: /api/users
├── layout.tsx # Root layout (<html>, <body>)
├── page.tsx # /
├── loading.tsx # Suspense fallback for the segment
├── error.tsx # Error boundary ('use client')
└── not-found.tsx # Rendered by notFound()
proxy.ts # Request interception (middleware.ts before v16)
```
A route group does not add a URL segment, so `(dashboard)/page.tsx` would serve `/`, not `/dashboard`; put the page under a `dashboard/` folder as shown.
## Routing files
- `page.tsx` makes a segment public; `layout.tsx` wraps it and persists across navigation.
- `loading.tsx` shows while the page streams; `error.tsx` must be a Client Component and receives `error` plus `retry()` (Next.js 16.3+) or `reset()`.
- `not-found.tsx` renders when `notFound()` is called.
- A segment cannot have both `page.tsx` and `route.ts`.
## Route Handlers
Validate input, return explicit status codes and never pass the raw body to the database.
```ts
// app/api/users/route.ts
import { NextResponse, type NextRequest } from 'next/server'
import { z } from 'zod'
import { db } from '@/lib/db'
const createUser = z.object({ email: z.email(), name: z.string().min(1).max(100) })
export async function GET(request: NextRequest) {
const page = Math.max(1, Number(request.nextUrl.searchParams.get('page') ?? '1') || 1)
const users = await db.user.findMany({ skip: (page - 1) * 10, take: 10 })
return NextResponse.json({ users, page })
}
export async function POST(request: NextRequest) {
const parsed = createUser.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return NextResponse.json({ error: 'Validation failed', issues: parsed.error.issues }, { status: 400 })
}
const user = await db.user.create({ data: parsed.data })
return NextResponse.json({ user }, { status: 201 })
}
```
Add authentication and authorization inside each handler that reads or writes private data. Prefer Server Components for reads and Server Actions for your own forms; use Route Handlers for webhooks and external clients.
## Metadata
```tsx
// app/products/[id]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { getProduct } from '@/lib/products'
type Props = { params: Promise<{ id: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
return { title: product.name, description: product.description, alternates: { canonical: `/products/${id}` } }
}
export default async function Page({ params }: Props) {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
return <h1>{product.name}</h1>
}
```
Set `metadataBase` and a `title.template` once in the root layout.
## Proxy (request interception)
Use it for redirects, rewrites and optimistic checks on a cookie. Do not query the database there, and do not rely on it as the only authorization check.
```ts
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
if (!request.cookies.has('session') && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
export const config = { matcher: ['/dashboard/:path*'] }
```
Upgrading an existing project: `npx @next/codemod@canary middleware-to-proxy .`
## Verify before finishing
- `npx tsc --noEmit` and `npx next build` pass.
- `curl -X POST localhost:3000/api/users -H 'content-type: application/json' -d '{}'` returns 400 with `issues`; a valid body returns 201.
- Visiting `/dashboard` without the session cookie redirects to `/login`, and the protected data functions still reject requests without a session.
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 rules for React with TypeScript: typed function components, React 19 ref-as-prop, hooks discipline, state ownership, error boundaries and measured performance work.
Cursor
fullstack
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Starting work in an App Router codebase that was written for Next.js 14 and has just been upgraded to Next.js 16.
We upgraded from Next.js 14 to 16. app/api/users/route.ts does db.user.create({ data: await request.json() }), pages use params.id synchronously, and middleware.ts redirects /dashboard without a token cookie. Bring these files up to date.Illustrative; not a recorded model run. Route Handler validates the body with a Zod 4 schema via safeParse and returns 400 with issues or 201; GET clamps page; pages and generateMetadata type params as Promise and await them; middleware.ts becomes proxy.ts exporting proxy (codemod named) and still only checks the cookie; a reminder that data functions must enforce auth too.
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-14-app-router-complete-guide.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 14 App Router Complete Guide, Updated for Next.js 16 project conventions"
globs: "**/*"
alwaysApply: false
---
# Next.js App Router Guide (Next.js 14+, updated for Next.js 16)
Applies to: day-to-day work in a Next.js App Router project: project layout, routing files, Route Handlers, metadata and request interception.
Version baseline: originally written for Next.js 14; checked against the Next.js 16.3 documentation. Read `package.json` before writing code and apply the version notes below:
- Next.js 15+: `params`, `searchParams`, `cookies()` and `headers()` are async. Await them.
- Next.js 16: `middleware.ts` is deprecated and renamed `proxy.ts` (export `proxy`); `fetch` is not cached by default, and the Cache Components model (`'use cache'`) replaces `unstable_cache`.
- On Next.js 14, keep synchronous `params` and `middleware.ts`.
## Project structure
```
app/
├── (auth)/ # Route group (no URL segment)
│ ├── login/page.tsx # /login
│ └── signup/page.tsx # /signup
├── (dashboard)/
│ ├── layout.tsx # Shared dashboard layout
│ └── dashboard/
│ ├── page.tsx # /dashboard
│ └── settings/page.tsx # /dashboard/settings
├── api/users/route.ts # Route Handler: /api/users
├── layout.tsx # Root layout (<html>, <body>)
├── page.tsx # /
├── loading.tsx # Suspense fallback for the segment
├── error.tsx # Error boundary ('use client')
└── not-found.tsx # Rendered by notFound()
proxy.ts # Request interception (middleware.ts before v16)
```
A route group does not add a URL segment, so `(dashboard)/page.tsx` would serve `/`, not `/dashboard`; put the page under a `dashboard/` folder as shown.
## Routing files
- `page.tsx` makes a segment public; `layout.tsx` wraps it and persists across navigation.
- `loading.tsx` shows while the page streams; `error.tsx` must be a Client Component and receives `error` plus `retry()` (Next.js 16.3+) or `reset()`.
- `not-found.tsx` renders when `notFound()` is called.
- A segment cannot have both `page.tsx` and `route.ts`.
## Route Handlers
Validate input, return explicit status codes and never pass the raw body to the database.
```ts
// app/api/users/route.ts
import { NextResponse, type NextRequest } from 'next/server'
import { z } from 'zod'
import { db } from '@/lib/db'
const createUser = z.object({ email: z.email(), name: z.string().min(1).max(100) })
export async function GET(request: NextRequest) {
const page = Math.max(1, Number(request.nextUrl.searchParams.get('page') ?? '1') || 1)
const users = await db.user.findMany({ skip: (page - 1) * 10, take: 10 })
return NextResponse.json({ users, page })
}
export async function POST(request: NextRequest) {
const parsed = createUser.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return NextResponse.json({ error: 'Validation failed', issues: parsed.error.issues }, { status: 400 })
}
const user = await db.user.create({ data: parsed.data })
return NextResponse.json({ user }, { status: 201 })
}
```
Add authentication and authorization inside each handler that reads or writes private data. Prefer Server Components for reads and Server Actions for your own forms; use Route Handlers for webhooks and external clients.
## Metadata
```tsx
// app/products/[id]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { getProduct } from '@/lib/products'
type Props = { params: Promise<{ id: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
return { title: product.name, description: product.description, alternates: { canonical: `/products/${id}` } }
}
export default async function Page({ params }: Props) {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
return <h1>{product.name}</h1>
}
```
Set `metadataBase` and a `title.template` once in the root layout.
## Proxy (request interception)
Use it for redirects, rewrites and optimistic checks on a cookie. Do not query the database there, and do not rely on it as the only authorization check.
```ts
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
if (!request.cookies.has('session') && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
export const config = { matcher: ['/dashboard/:path*'] }
```
Upgrading an existing project: `npx @next/codemod@canary middleware-to-proxy .`
## Verify before finishing
- `npx tsc --noEmit` and `npx next build` pass.
- `curl -X POST localhost:3000/api/users -H 'content-type: application/json' -d '{}'` returns 400 with `issues`; a valid body returns 201.
- Visiting `/dashboard` without the session cookie redirects to `/login`, and the protected data functions still reject requests without a session.
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 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 rules for React with TypeScript: typed function components, React 19 ref-as-prop, hooks discipline, state ownership, error boundaries and measured performance work.