CLAUDE.md rules for the Next.js 16 App Router with async params, streaming via Suspense, secured Server Actions, metadata conventions and explicit caching choices.
.claude/rules/claude-nextjs-expert.md. Downloaded files need to be placed in that repository path.---
paths:
- "**/*"
---
# Next.js App Router Conventions
Applies to: the Next.js App Router code in this repository (`app/`, Server Actions, Route Handlers, metadata).
Version baseline: checked against Next.js 16.3 and React 19.2. Read `package.json` and `next.config.ts` first. Next.js 15 and 16 changed `params`, caching defaults and middleware, so follow the installed version's docs (bundled in `node_modules/next/dist/docs` on recent releases) when they differ from your memory.
## Server and Client Components
- Components in `app/` are Server Components by default. Fetch data in them directly with `async`/`await` (no `useEffect`).
- Add `'use client'` only to leaf components that need state, effects, event handlers or browser APIs. Pass them serializable props.
- To stream slow data, move the slow fetch into its own async component and wrap that component in `<Suspense>`. A `<Suspense>` around data that is already awaited above it does nothing.
```tsx
// app/products/page.tsx
import { Suspense } from 'react';
import { ProductGrid, ProductGridSkeleton } from './product-grid';
export default function ProductsPage() {
return (
<main>
<h1>Products</h1>
<Suspense fallback={<ProductGridSkeleton />}>
<ProductGrid />
</Suspense>
</main>
);
}
```
```tsx
// app/products/product-grid.tsx
import { prisma } from '@/lib/prisma';
export async function ProductGrid() {
const products = await prisma.product.findMany({
where: { published: true },
orderBy: { createdAt: 'desc' },
select: { id: true, name: true },
});
return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
export function ProductGridSkeleton() {
return <p aria-busy="true">Loading products...</p>;
}
```
## Dynamic routes and metadata
- `params` and `searchParams` are Promises in pages, layouts, Route Handlers and `generateMetadata`. Type them as `Promise<...>` and await them.
- Set `metadataBase` in the root layout, use relative `alternates.canonical` per page, and use `opengraph-image.tsx`, `sitemap.ts` and `robots.ts` file conventions instead of hand-written tags.
```tsx
// app/products/[id]/page.tsx
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getProduct } from '@/lib/data/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) return {};
return {
title: product.name,
description: product.description,
alternates: { canonical: `/products/${id}` },
openGraph: { images: product.image ? [product.image] : [] },
};
}
export default async function ProductPage({ params }: Props) {
const { id } = await params;
const product = await getProduct(id);
if (!product) notFound();
return <h1>{product.name}</h1>;
}
```
## Server Actions
- Treat each action as a public POST endpoint. Authenticate, authorize and validate (for example with Zod) inside the action, and never rely only on hiding the form.
- After a write, invalidate what changed, then `redirect()`. `redirect` throws, so call it outside `try/catch`.
- Return expected errors as values for `useActionState`, and throw only for unexpected failures.
```ts
// app/products/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { requireUser } from '@/lib/auth';
const Input = z.object({ name: z.string().trim().min(1), priceCents: z.coerce.number().int().min(0) });
export async function createProduct(_prev: { error?: string }, formData: FormData) {
await requireUser();
const parsed = Input.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { error: 'Name and a non-negative price are required.' };
const product = await prisma.product.create({ data: parsed.data });
revalidatePath('/products');
redirect(`/products/${product.id}`);
}
```
## Caching
- `fetch` is not cached by default. When `cacheComponents` is enabled, cache with `'use cache'` plus `cacheLife`/`cacheTag`, and invalidate with `updateTag` (Server Actions) or `revalidateTag(tag, 'max')`.
- Without Cache Components, use `revalidatePath`/`revalidateTag(tag, 'max')`. `unstable_cache` has been replaced by `'use cache'` in Next.js 16.
- When you add or change data access, state what is cached, for how long, and what invalidates it.
## Routing files and runtime
- Use `loading.tsx`, `error.tsx` (a Client Component, with a `retry` prop on 16.3+), `not-found.tsx` and `global-error.tsx` per segment as needed.
- Use `proxy.ts` (renamed from `middleware.ts` in Next.js 16) only for optimistic checks, redirects and rewrites. Do authorization next to the data.
- Keep the default Node.js runtime unless a route has a documented reason to run on Edge.
## Verify before finishing
Run when available: `npx tsc --noEmit`, `npx eslint .` (`next lint` was removed in 16), the project's tests, and `npx next build`. Report any route whose rendering mode (static or dynamic) changed in the build output.
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.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
CLAUDE.md rules for React 19 with TypeScript covering typed components, derived state, compiler-aware memoization, useId-based accessibility and review checks.
Claude
fullstack
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Claude Code edits a Next.js 16 App Router project with this file loaded as a project rule (for example .claude/rules/nextjs.md scoped to app/**).
Add /products/[id] with title, description and canonical metadata, and make /products stream its grid while the header renders immediately. Also add a createProduct action that redirects to the new product. lib/prisma.ts and lib/auth.ts (requireUser) exist; cacheComponents is off.
Illustrative; not a recorded model run. A page and generateMetadata typed with params: Promise<{ id: string }> and awaited, returning {} or notFound() for a missing product, and a relative alternates.canonical; the slow Prisma query moved into an async ProductGrid wrapped in <Suspense> with a skeleton; a 'use server' action that calls requireUser, validates with Zod, creates the product, calls revalidatePath('/products') and then redirect() outside any try/catch; a note on what is cached and invalidated; tsc, eslint and next build results.Claude Code loads persistent project instructions from CLAUDE.md files and from Markdown rules in .claude/rules/. Rules can be scoped to file paths with a paths frontmatter field, and CLAUDE.md can import other files with @path syntax. The rules in this directory are written as plain instruction prompts: in Claude Code, save them as CLAUDE.md or .claude/rules/ content; in Claude.ai or the Claude API, use the same text as project instructions or a system prompt instead.
.claude/rules/claude-nextjs-expert.mdStarting point, not a tested configuration for your repository. Loaded when Claude Code works with files matching paths. Review the instructions, adapt the file paths and run your project's existing checks.
---
paths:
- "**/*"
---
# Next.js App Router Conventions
Applies to: the Next.js App Router code in this repository (`app/`, Server Actions, Route Handlers, metadata).
Version baseline: checked against Next.js 16.3 and React 19.2. Read `package.json` and `next.config.ts` first. Next.js 15 and 16 changed `params`, caching defaults and middleware, so follow the installed version's docs (bundled in `node_modules/next/dist/docs` on recent releases) when they differ from your memory.
## Server and Client Components
- Components in `app/` are Server Components by default. Fetch data in them directly with `async`/`await` (no `useEffect`).
- Add `'use client'` only to leaf components that need state, effects, event handlers or browser APIs. Pass them serializable props.
- To stream slow data, move the slow fetch into its own async component and wrap that component in `<Suspense>`. A `<Suspense>` around data that is already awaited above it does nothing.
```tsx
// app/products/page.tsx
import { Suspense } from 'react';
import { ProductGrid, ProductGridSkeleton } from './product-grid';
export default function ProductsPage() {
return (
<main>
<h1>Products</h1>
<Suspense fallback={<ProductGridSkeleton />}>
<ProductGrid />
</Suspense>
</main>
);
}
```
```tsx
// app/products/product-grid.tsx
import { prisma } from '@/lib/prisma';
export async function ProductGrid() {
const products = await prisma.product.findMany({
where: { published: true },
orderBy: { createdAt: 'desc' },
select: { id: true, name: true },
});
return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
export function ProductGridSkeleton() {
return <p aria-busy="true">Loading products...</p>;
}
```
## Dynamic routes and metadata
- `params` and `searchParams` are Promises in pages, layouts, Route Handlers and `generateMetadata`. Type them as `Promise<...>` and await them.
- Set `metadataBase` in the root layout, use relative `alternates.canonical` per page, and use `opengraph-image.tsx`, `sitemap.ts` and `robots.ts` file conventions instead of hand-written tags.
```tsx
// app/products/[id]/page.tsx
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getProduct } from '@/lib/data/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) return {};
return {
title: product.name,
description: product.description,
alternates: { canonical: `/products/${id}` },
openGraph: { images: product.image ? [product.image] : [] },
};
}
export default async function ProductPage({ params }: Props) {
const { id } = await params;
const product = await getProduct(id);
if (!product) notFound();
return <h1>{product.name}</h1>;
}
```
## Server Actions
- Treat each action as a public POST endpoint. Authenticate, authorize and validate (for example with Zod) inside the action, and never rely only on hiding the form.
- After a write, invalidate what changed, then `redirect()`. `redirect` throws, so call it outside `try/catch`.
- Return expected errors as values for `useActionState`, and throw only for unexpected failures.
```ts
// app/products/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { requireUser } from '@/lib/auth';
const Input = z.object({ name: z.string().trim().min(1), priceCents: z.coerce.number().int().min(0) });
export async function createProduct(_prev: { error?: string }, formData: FormData) {
await requireUser();
const parsed = Input.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { error: 'Name and a non-negative price are required.' };
const product = await prisma.product.create({ data: parsed.data });
revalidatePath('/products');
redirect(`/products/${product.id}`);
}
```
## Caching
- `fetch` is not cached by default. When `cacheComponents` is enabled, cache with `'use cache'` plus `cacheLife`/`cacheTag`, and invalidate with `updateTag` (Server Actions) or `revalidateTag(tag, 'max')`.
- Without Cache Components, use `revalidatePath`/`revalidateTag(tag, 'max')`. `unstable_cache` has been replaced by `'use cache'` in Next.js 16.
- When you add or change data access, state what is cached, for how long, and what invalidates it.
## Routing files and runtime
- Use `loading.tsx`, `error.tsx` (a Client Component, with a `retry` prop on 16.3+), `not-found.tsx` and `global-error.tsx` per segment as needed.
- Use `proxy.ts` (renamed from `middleware.ts` in Next.js 16) only for optimistic checks, redirects and rewrites. Do authorization next to the data.
- Keep the default Node.js runtime unless a route has a documented reason to run on Edge.
## Verify before finishing
Run when available: `npx tsc --noEmit`, `npx eslint .` (`next lint` was removed in 16), the project's tests, and `npx next build`. Report any route whose rendering mode (static or dynamic) changed in the build output.
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.
Imports with @path can nest up to four hops deep, according to the docs. Claude Code can read AGENTS.md as project instructions without extra configuration, but by default only when there is no CLAUDE.md in the working directory or above it. The docs list this behavior for version 2.1.277 and later and describe a setting (claude-md-and-agents-md) that loads both files. If you maintain AGENTS.md for other tools, you can also import it from CLAUDE.md with @AGENTS.md.
Documentation checked 2026-11-05: Claude Code docs: Manage Claude's memory
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.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
CLAUDE.md rules for React 19 with TypeScript covering typed components, derived state, compiler-aware memoization, useId-based accessibility and review checks.