Cursor rule for structuring Next.js App Router routes with route groups, special files, async params, parallel slots with default files and intercepted modal routes.
.cursor/rules/next-js-app-router-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for structuring Next.js App Router routes with route groups, special files, async params, parallel slots with default files and intercepted modal routes."
globs: "**/*"
alwaysApply: false
---
# Next.js App Router Patterns
Applies to: route structure and special files under `app/` in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 documentation. Read `package.json` first; if the project pins an older major, follow that version's conventions (for example `middleware.ts` instead of `proxy.ts`, synchronous `params` before Next.js 15).
## Organize routes by URL first
- A folder becomes a URL segment only when it contains `page.tsx` or `route.ts`. Colocate components, tests and helpers inside route folders when they belong to one route; prefix private folders with `_` (for example `_components`) so they can never become routes.
- Use route groups `(name)` to share a layout or split the app into sections without changing the URL: `app/(marketing)/about/page.tsx` serves `/about`.
- Two groups must not resolve to the same URL (`(a)/about` and `(b)/about` conflict). Multiple root layouts (one per group, each with `<html>` and `<body>`) cause a full page load when navigating between them; use them deliberately.
## Special files and what they wrap
- `layout.tsx` persists across navigation and does not re-render; do not read per-request data there that must update on every navigation.
- `loading.tsx` wraps the segment's `page.tsx` in a Suspense boundary. Prefer explicit `<Suspense>` around the slow part of a page when only that part waits.
- `error.tsx` must start with `'use client'`. It catches errors in the segment's page and nested layouts but not in the layout of the same segment; handle root-layout failures with `app/global-error.tsx`.
- `not-found.tsx` renders when `notFound()` from `next/navigation` is called in that segment.
## Dynamic segments
`params` is a Promise in Next.js 15 and later. Await it.
```tsx
// app/shop/[slug]/page.tsx
import { notFound } from 'next/navigation'
import { db } from '@/lib/db'
export default async function ProductPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await db.product.findUnique({ where: { id: slug } })
if (!product) notFound()
return <h1>{product.name}</h1>
}
```
After `next typegen`, `next dev` or `next build` has generated route types, the global `PageProps<'/shop/[slug]'>` helper can type the same props.
## Parallel routes (`@slot`)
- Use named slots when one layout renders independent panels (for example `@analytics` and `@team`) that load or fail separately.
- Every slot needs a `default.tsx` fallback, and so does the implicit `children` slot when its sibling slots have sub-pages. Without it a hard refresh on an unmatched URL renders a 404.
```tsx
// app/dashboard/layout.tsx
export default function DashboardLayout({
children,
analytics,
team,
}: {
children: React.ReactNode
analytics: React.ReactNode
team: React.ReactNode
}) {
return (
<section>
{children}
<div className="grid grid-cols-2 gap-4">
{analytics}
{team}
</div>
</section>
)
}
```
```tsx
// app/dashboard/@analytics/default.tsx
export default function AnalyticsDefault() {
return null
}
```
## Intercepting routes for modals
- Pair a parallel `@modal` slot with an intercepting folder such as `app/@modal/(.)photo/[id]/page.tsx` so a client-side navigation to `/photo/123` shows a modal while a direct visit or refresh renders the full `app/photo/[id]/page.tsx`.
- The `(.)`, `(..)` and `(...)` markers are based on route segments, not file-system folders; slots and groups do not count.
- Give `@modal` a `default.tsx` returning `null` so the modal closes on other routes, and close it with `router.back()` in the client modal.
## Route handlers
- `route.ts` exports HTTP method functions (`GET`, `POST`, ...). A folder cannot contain both `route.ts` and `page.tsx`.
- Prefer Server Components for reading data in your own UI and Server Actions for your own form mutations; use route handlers for webhooks, third-party clients and non-HTML responses.
## Verify before finishing
- Run `npx next build` when available: it reports route conflicts, missing default files and type errors in generated route types.
- Run `npx tsc --noEmit` to catch synchronous `params` access.
- Manually test each parallel or intercepted route twice: once by client navigation and once by hard refresh.
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
framework
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Adding a dashboard with two independently loading panels and a photo modal that must also work as a full page on refresh, in a Next.js 16 App Router project with this rule attached.
Add /dashboard with @analytics and @team panels that load separately, and make /photo/[id] open as a modal from the gallery but as a full page when visited directly. Current tree: app/layout.tsx, app/page.tsx, app/gallery/page.tsx, app/photo/[id]/page.tsx.
Illustrative; not a recorded model run. A file plan plus code: app/dashboard/layout.tsx receiving children, analytics and team props; app/dashboard/@analytics/default.tsx and @team/default.tsx (plus app/dashboard/default.tsx if the slots have sub-pages); app/@modal/(.)photo/[id]/page.tsx rendering a client modal that closes with router.back(); app/@modal/default.tsx returning null; app/layout.tsx rendering {modal}; every dynamic page typed with params: Promise<...> and awaiting it; a note to test soft and hard navigation.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/next-js-app-router-patterns.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 App Router Patterns: Route Groups, Parallel and Intercepting Routes project conventions"
globs: "**/*"
alwaysApply: false
---
# Next.js App Router Patterns
Applies to: route structure and special files under `app/` in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 documentation. Read `package.json` first; if the project pins an older major, follow that version's conventions (for example `middleware.ts` instead of `proxy.ts`, synchronous `params` before Next.js 15).
## Organize routes by URL first
- A folder becomes a URL segment only when it contains `page.tsx` or `route.ts`. Colocate components, tests and helpers inside route folders when they belong to one route; prefix private folders with `_` (for example `_components`) so they can never become routes.
- Use route groups `(name)` to share a layout or split the app into sections without changing the URL: `app/(marketing)/about/page.tsx` serves `/about`.
- Two groups must not resolve to the same URL (`(a)/about` and `(b)/about` conflict). Multiple root layouts (one per group, each with `<html>` and `<body>`) cause a full page load when navigating between them; use them deliberately.
## Special files and what they wrap
- `layout.tsx` persists across navigation and does not re-render; do not read per-request data there that must update on every navigation.
- `loading.tsx` wraps the segment's `page.tsx` in a Suspense boundary. Prefer explicit `<Suspense>` around the slow part of a page when only that part waits.
- `error.tsx` must start with `'use client'`. It catches errors in the segment's page and nested layouts but not in the layout of the same segment; handle root-layout failures with `app/global-error.tsx`.
- `not-found.tsx` renders when `notFound()` from `next/navigation` is called in that segment.
## Dynamic segments
`params` is a Promise in Next.js 15 and later. Await it.
```tsx
// app/shop/[slug]/page.tsx
import { notFound } from 'next/navigation'
import { db } from '@/lib/db'
export default async function ProductPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await db.product.findUnique({ where: { id: slug } })
if (!product) notFound()
return <h1>{product.name}</h1>
}
```
After `next typegen`, `next dev` or `next build` has generated route types, the global `PageProps<'/shop/[slug]'>` helper can type the same props.
## Parallel routes (`@slot`)
- Use named slots when one layout renders independent panels (for example `@analytics` and `@team`) that load or fail separately.
- Every slot needs a `default.tsx` fallback, and so does the implicit `children` slot when its sibling slots have sub-pages. Without it a hard refresh on an unmatched URL renders a 404.
```tsx
// app/dashboard/layout.tsx
export default function DashboardLayout({
children,
analytics,
team,
}: {
children: React.ReactNode
analytics: React.ReactNode
team: React.ReactNode
}) {
return (
<section>
{children}
<div className="grid grid-cols-2 gap-4">
{analytics}
{team}
</div>
</section>
)
}
```
```tsx
// app/dashboard/@analytics/default.tsx
export default function AnalyticsDefault() {
return null
}
```
## Intercepting routes for modals
- Pair a parallel `@modal` slot with an intercepting folder such as `app/@modal/(.)photo/[id]/page.tsx` so a client-side navigation to `/photo/123` shows a modal while a direct visit or refresh renders the full `app/photo/[id]/page.tsx`.
- The `(.)`, `(..)` and `(...)` markers are based on route segments, not file-system folders; slots and groups do not count.
- Give `@modal` a `default.tsx` returning `null` so the modal closes on other routes, and close it with `router.back()` in the client modal.
## Route handlers
- `route.ts` exports HTTP method functions (`GET`, `POST`, ...). A folder cannot contain both `route.ts` and `page.tsx`.
- Prefer Server Components for reading data in your own UI and Server Actions for your own form mutations; use route handlers for webhooks, third-party clients and non-HTML responses.
## Verify before finishing
- Run `npx next build` when available: it reports route conflicts, missing default files and type errors in generated route types.
- Run `npx tsc --noEmit` to catch synchronous `params` access.
- Manually test each parallel or intercepted route twice: once by client navigation and once by hard refresh.
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.