Cursor rule for React Server Components in the Next.js App Router covering client boundaries, serializable props, async params, streaming and secure Server Actions.
.cursor/rules/react-server-components-guide.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for React Server Components in the Next.js App Router covering client boundaries, serializable props, async params, streaming and secure Server Actions."
globs: "**/*"
alwaysApply: false
---
# React Server Components Guide (Next.js App Router)
Applies to: Next.js App Router code under `app/` (pages, layouts, components, Server Actions) that mixes Server and Client Components.
Version baseline: checked against the Next.js 16.3 documentation and React 19. Since Next.js 15, `params` and `searchParams` are Promises. Next.js 16 replaces `unstable_cache` with `'use cache'` (Cache Components). Read the `next` version in `package.json` and whether `cacheComponents` is enabled in `next.config.*`, and follow the matching docs.
## Server vs Client Components
- Components in `app/` are Server Components by default (no directive). They can be `async`, read data directly, and keep secrets and large dependencies off the client.
- Add `'use client'` only at the top of a file that needs:
- state or effects (`useState`, `useEffect`, other client hooks),
- browser APIs (`window`, `document`, `localStorage`),
- event handlers (`onClick`, `onChange`),
- class components (including error boundaries) or client-only libraries.
- `'use client'` marks a boundary: that file and everything it imports become client code. Put the directive on small leaf components (a button, a form), not on layouts or pages.
- Server Components can render Client Components and pass Server Components to them as `children` or other props.
## Props across the boundary
- Props passed from a Server to a Client Component must be serializable by React: plain objects, arrays, strings, numbers, booleans, `null`, `Date`, `Map`/`Set`, Promises, JSX, and Server Functions. Do not pass class instances or ordinary functions.
- Pass only the fields the client needs. Never pass whole database rows that contain secrets. Add `import "server-only"` to modules that must never be bundled for the client (database access, secret keys).
## Data fetching
```tsx
// app/products/[id]/page.tsx
import { Suspense } from "react";
import { notFound } from "next/navigation";
import { getProduct, getReviews } from "@/lib/data"; // server-only module
import { AddToCartButton } from "./add-to-cart-button"; // 'use client' leaf
import { Reviews } from "./reviews"; // 'use client' component that calls use(reviews)
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await getProduct(id);
if (!product) notFound();
return (
<main>
<h1>{product.name}</h1>
<AddToCartButton productId={product.id} />
<Suspense fallback={<p>Loading reviews…</p>}>
<Reviews reviews={getReviews(id)} /> {/* pass the promise; do not await it here */}
</Suspense>
</main>
);
}
```
- Start independent requests together, and await them with `Promise.all` (or `Promise.allSettled` if one may fail) to avoid waterfalls:
```tsx
const [user, stats] = await Promise.all([getUser(), getStats()]);
```
- Wrap shared data functions in React's `cache()` so several components in one request reuse one result.
- `fetch` is not cached by default in current Next.js. Decide caching explicitly (see Caching).
## Streaming with Suspense
- Wrap slow, independent sections in `<Suspense fallback>` so the rest of the page renders first. Add `loading.tsx` for a whole-segment fallback during navigation.
- Make fallbacks match the final layout size to avoid layout shift.
## Server Actions
```tsx
// app/posts/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { getSession } from "@/lib/auth"; // project auth helper
import { db } from "@/lib/db";
const PostInput = z.object({
title: z.string().trim().min(1, "Title is required").max(200),
content: z.string().trim().min(1, "Content is required"),
});
export type CreatePostState = { errors?: Record<string, string[] | undefined>; ok?: boolean };
export async function createPost(_prev: CreatePostState, formData: FormData): Promise<CreatePostState> {
const session = await getSession();
if (!session) return { errors: { form: ["Sign in to post."] } };
const parsed = PostInput.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { errors: z.flattenError(parsed.error).fieldErrors };
await db.post.create({ data: { ...parsed.data, authorId: session.userId } });
revalidatePath("/posts");
return { ok: true };
}
```
- Every Server Action is a public POST endpoint. Authenticate, authorize and validate inside each action, even if the form only renders for signed-in users.
- Return serializable results for expected errors (and use them with `useActionState`). Throw only for unexpected failures.
## Caching
- Request deduplication: use React `cache()` for per-request memoisation.
- With Cache Components (`cacheComponents: true`), cache data or UI with the `'use cache'` directive, set a lifetime with `cacheLife(...)`, tag entries with `cacheTag(...)`, and invalidate with `updateTag(tag)` (Server Actions, read-your-writes) or `revalidateTag(tag, "max")`. `unstable_cache` is superseded by `'use cache'` in Next.js 16.
- Without Cache Components (the previous model), use `fetch` cache options, `revalidatePath`/`revalidateTag`, and route segment config (`export const revalidate = 60`) as documented in "Caching without Cache Components".
- After a mutation, invalidate exactly the paths or tags whose data changed.
## Verify before finishing
- `npx tsc --noEmit` and `next build` succeed. The build output shows which routes are static or dynamic. Confirm that this matches the intent.
- No `'use client'` file imports server-only modules (the `server-only` import makes this a build error).
- Each Server Action has an auth check, input validation and a test for its invalid-input path.
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
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A developer asks Cursor to build a product page and a create-post action in a Next.js 16 App Router project without shipping unnecessary client JavaScript.
app/products/[id]/page.tsx is marked 'use client', fetches the product in useEffect and types params as { id: string }. Reviews load slowly. Also add a createPost Server Action with validation. Next 16.3, React 19.2, zod 4, cacheComponents off.Illustrative; not a recorded model run. The page becomes an async Server Component that awaits params (Promise<{ id: string }>), calls notFound() for missing products, and keeps 'use client' only on AddToCartButton and the Reviews leaf. The reviews promise is passed un-awaited inside <Suspense>. data.ts imports 'server-only'. createPost in actions.ts checks the session, validates with zod safeParse and z.flattenError, writes, calls revalidatePath('/posts') and returns serializable state. The answer explains that fetch is not cached by default and which caching model applies with cacheComponents off.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/react-server-components-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: "React Server Components Guide: Next.js 16 App Router Boundaries, Streaming, Actions and Caching project conventions"
globs: "**/*"
alwaysApply: false
---
# React Server Components Guide (Next.js App Router)
Applies to: Next.js App Router code under `app/` (pages, layouts, components, Server Actions) that mixes Server and Client Components.
Version baseline: checked against the Next.js 16.3 documentation and React 19. Since Next.js 15, `params` and `searchParams` are Promises. Next.js 16 replaces `unstable_cache` with `'use cache'` (Cache Components). Read the `next` version in `package.json` and whether `cacheComponents` is enabled in `next.config.*`, and follow the matching docs.
## Server vs Client Components
- Components in `app/` are Server Components by default (no directive). They can be `async`, read data directly, and keep secrets and large dependencies off the client.
- Add `'use client'` only at the top of a file that needs:
- state or effects (`useState`, `useEffect`, other client hooks),
- browser APIs (`window`, `document`, `localStorage`),
- event handlers (`onClick`, `onChange`),
- class components (including error boundaries) or client-only libraries.
- `'use client'` marks a boundary: that file and everything it imports become client code. Put the directive on small leaf components (a button, a form), not on layouts or pages.
- Server Components can render Client Components and pass Server Components to them as `children` or other props.
## Props across the boundary
- Props passed from a Server to a Client Component must be serializable by React: plain objects, arrays, strings, numbers, booleans, `null`, `Date`, `Map`/`Set`, Promises, JSX, and Server Functions. Do not pass class instances or ordinary functions.
- Pass only the fields the client needs. Never pass whole database rows that contain secrets. Add `import "server-only"` to modules that must never be bundled for the client (database access, secret keys).
## Data fetching
```tsx
// app/products/[id]/page.tsx
import { Suspense } from "react";
import { notFound } from "next/navigation";
import { getProduct, getReviews } from "@/lib/data"; // server-only module
import { AddToCartButton } from "./add-to-cart-button"; // 'use client' leaf
import { Reviews } from "./reviews"; // 'use client' component that calls use(reviews)
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await getProduct(id);
if (!product) notFound();
return (
<main>
<h1>{product.name}</h1>
<AddToCartButton productId={product.id} />
<Suspense fallback={<p>Loading reviews…</p>}>
<Reviews reviews={getReviews(id)} /> {/* pass the promise; do not await it here */}
</Suspense>
</main>
);
}
```
- Start independent requests together, and await them with `Promise.all` (or `Promise.allSettled` if one may fail) to avoid waterfalls:
```tsx
const [user, stats] = await Promise.all([getUser(), getStats()]);
```
- Wrap shared data functions in React's `cache()` so several components in one request reuse one result.
- `fetch` is not cached by default in current Next.js. Decide caching explicitly (see Caching).
## Streaming with Suspense
- Wrap slow, independent sections in `<Suspense fallback>` so the rest of the page renders first. Add `loading.tsx` for a whole-segment fallback during navigation.
- Make fallbacks match the final layout size to avoid layout shift.
## Server Actions
```tsx
// app/posts/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { getSession } from "@/lib/auth"; // project auth helper
import { db } from "@/lib/db";
const PostInput = z.object({
title: z.string().trim().min(1, "Title is required").max(200),
content: z.string().trim().min(1, "Content is required"),
});
export type CreatePostState = { errors?: Record<string, string[] | undefined>; ok?: boolean };
export async function createPost(_prev: CreatePostState, formData: FormData): Promise<CreatePostState> {
const session = await getSession();
if (!session) return { errors: { form: ["Sign in to post."] } };
const parsed = PostInput.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { errors: z.flattenError(parsed.error).fieldErrors };
await db.post.create({ data: { ...parsed.data, authorId: session.userId } });
revalidatePath("/posts");
return { ok: true };
}
```
- Every Server Action is a public POST endpoint. Authenticate, authorize and validate inside each action, even if the form only renders for signed-in users.
- Return serializable results for expected errors (and use them with `useActionState`). Throw only for unexpected failures.
## Caching
- Request deduplication: use React `cache()` for per-request memoisation.
- With Cache Components (`cacheComponents: true`), cache data or UI with the `'use cache'` directive, set a lifetime with `cacheLife(...)`, tag entries with `cacheTag(...)`, and invalidate with `updateTag(tag)` (Server Actions, read-your-writes) or `revalidateTag(tag, "max")`. `unstable_cache` is superseded by `'use cache'` in Next.js 16.
- Without Cache Components (the previous model), use `fetch` cache options, `revalidatePath`/`revalidateTag`, and route segment config (`export const revalidate = 60`) as documented in "Caching without Cache Components".
- After a mutation, invalidate exactly the paths or tags whose data changed.
## Verify before finishing
- `npx tsc --noEmit` and `next build` succeed. The build output shows which routes are static or dynamic. Confirm that this matches the intent.
- No `'use client'` file imports server-only modules (the `server-only` import makes this a build error).
- Each Server Action has an auth check, input validation and a test for its invalid-input path.
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.