Cursor rule for Next.js 16 data fetching with explicit use cache, cacheLife and cacheTag, updateTag after mutations, Suspense streaming and parallel requests.
.cursor/rules/next-js-data-fetching-strategies.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Next.js 16 data fetching with explicit use cache, cacheLife and cacheTag, updateTag after mutations, Suspense streaming and parallel requests."
globs: "**/*"
alwaysApply: false
---
# Next.js Data Fetching Strategies
Applies to: reading data in Server Components, caching it, and invalidating it after mutations in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 caching documentation. Read `package.json` and `next.config.*` first:
- If `cacheComponents: true` is set, use the `'use cache'` model below.
- If it is not set, follow the "Caching and Revalidating (Previous Model)" guide for that version (`fetch` options, route segment config) and do not mix in `'use cache'`.
- `unstable_cache` is replaced by `'use cache'` in Next.js 16; do not add new uses.
## Fetch where the data is used
- Fetch in the Server Component that renders the data. Identical `fetch` calls in one render are memoized, so you do not need to drill props to avoid duplicate requests.
- For non-`fetch` sources (ORM, SDK), wrap the read in a function in a server-only data module and, if several components call it per request, wrap it in React `cache()` for request deduplication.
## Freshness is explicit
- `fetch` is not cached by default. Opt in per call or per function; never assume a page is static.
- With Cache Components, cache data or UI with `'use cache'` and always pair it with `cacheLife`, plus `cacheTag` when the data can change from a mutation:
```ts
// lib/products.ts
import { cacheLife, cacheTag } from 'next/cache'
import { db } from '@/lib/db'
export async function getProduct(id: string) {
'use cache'
cacheLife('hours')
cacheTag('products', `product:${id}`)
return db.product.findUnique({ where: { id } })
}
```
- Cached functions cannot call `cookies()`, `headers()` or read `searchParams`, directly or through a helper. Read those outside and pass the values in as arguments; arguments become part of the cache key.
## Stream request-time data
Uncached or per-user reads belong inside `<Suspense>` so the rest of the page can be prerendered and streamed:
```tsx
// app/products/[id]/page.tsx
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getProduct } from '@/lib/products'
import { Reviews } from '@/app/products/[id]/reviews'
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
return (
<main>
<h1>{product.name}</h1>
<Suspense fallback={<p>Loading reviews...</p>}>
<Reviews productId={id} />
</Suspense>
</main>
)
}
```
## Avoid waterfalls
Start independent requests together and await them together. Keep sequential awaits only when a request needs the previous result.
```ts
// lib/dashboard.ts
import { db } from '@/lib/db'
export async function getDashboard(userId: string) {
const [user, posts] = await Promise.all([
db.user.findUnique({ where: { id: userId } }),
db.post.findMany({ where: { authorId: userId }, take: 10 }),
])
return { user, posts }
}
```
## Invalidate after mutations
- In a Server Action where the user must see their own change immediately, call `updateTag('product:<id>')` (Server Actions only).
- Elsewhere (Route Handlers, webhooks), call `revalidateTag(tag, 'max')`; the single-argument form is deprecated.
- `revalidatePath('/products')` remains available when the affected data is scoped to a path rather than a tag.
```ts
// app/products/actions.ts
'use server'
import { updateTag } from 'next/cache'
import { db } from '@/lib/db'
export async function renameProduct(id: string, name: string) {
// Authenticate and authorize here before writing.
await db.product.update({ where: { id }, data: { name } })
updateTag(`product:${id}`)
}
```
## Static params
- `generateStaticParams` lists params to prerender at build time. With Cache Components it must return at least one entry; an empty array is a build error.
- Without Cache Components, return an empty array (or use the previous model's options) to render paths on first visit.
## Verify before finishing
- `npx next build` succeeds and its route summary shows the rendering mode you intended for each changed route.
- In the dev overlay, no "blocking route" insight for the pages you changed.
- After a mutation, the edited value appears on the next request (for `updateTag`) or after background revalidation (for `revalidateTag(tag, 'max')`).
- `grep -rn "unstable_cache" app lib` returns no new uses.
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 .
A product page in a Next.js 16 app with cacheComponents enabled shows stale names after edits and loads reviews slowly.
next.config.ts has cacheComponents: true. app/products/[id]/page.tsx awaits getProduct(id) and then getReviews(id) sequentially, and renameProduct() in a Server Action updates the DB but the page keeps the old name. Fix caching and loading.
Illustrative; not a recorded model run. getProduct gains 'use cache', cacheLife('hours') and cacheTag('products', `product:${id}`); reviews move into a component inside <Suspense> with a fallback; params is awaited; renameProduct calls updateTag(`product:${id}`) after authorizing and writing; no unstable_cache; an explanation that revalidateTag(tag, 'max') is for non-action contexts.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-data-fetching-strategies.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 Data Fetching Strategies: use cache, Tags, Streaming and Parallel Requests project conventions"
globs: "**/*"
alwaysApply: false
---
# Next.js Data Fetching Strategies
Applies to: reading data in Server Components, caching it, and invalidating it after mutations in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 caching documentation. Read `package.json` and `next.config.*` first:
- If `cacheComponents: true` is set, use the `'use cache'` model below.
- If it is not set, follow the "Caching and Revalidating (Previous Model)" guide for that version (`fetch` options, route segment config) and do not mix in `'use cache'`.
- `unstable_cache` is replaced by `'use cache'` in Next.js 16; do not add new uses.
## Fetch where the data is used
- Fetch in the Server Component that renders the data. Identical `fetch` calls in one render are memoized, so you do not need to drill props to avoid duplicate requests.
- For non-`fetch` sources (ORM, SDK), wrap the read in a function in a server-only data module and, if several components call it per request, wrap it in React `cache()` for request deduplication.
## Freshness is explicit
- `fetch` is not cached by default. Opt in per call or per function; never assume a page is static.
- With Cache Components, cache data or UI with `'use cache'` and always pair it with `cacheLife`, plus `cacheTag` when the data can change from a mutation:
```ts
// lib/products.ts
import { cacheLife, cacheTag } from 'next/cache'
import { db } from '@/lib/db'
export async function getProduct(id: string) {
'use cache'
cacheLife('hours')
cacheTag('products', `product:${id}`)
return db.product.findUnique({ where: { id } })
}
```
- Cached functions cannot call `cookies()`, `headers()` or read `searchParams`, directly or through a helper. Read those outside and pass the values in as arguments; arguments become part of the cache key.
## Stream request-time data
Uncached or per-user reads belong inside `<Suspense>` so the rest of the page can be prerendered and streamed:
```tsx
// app/products/[id]/page.tsx
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getProduct } from '@/lib/products'
import { Reviews } from '@/app/products/[id]/reviews'
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
return (
<main>
<h1>{product.name}</h1>
<Suspense fallback={<p>Loading reviews...</p>}>
<Reviews productId={id} />
</Suspense>
</main>
)
}
```
## Avoid waterfalls
Start independent requests together and await them together. Keep sequential awaits only when a request needs the previous result.
```ts
// lib/dashboard.ts
import { db } from '@/lib/db'
export async function getDashboard(userId: string) {
const [user, posts] = await Promise.all([
db.user.findUnique({ where: { id: userId } }),
db.post.findMany({ where: { authorId: userId }, take: 10 }),
])
return { user, posts }
}
```
## Invalidate after mutations
- In a Server Action where the user must see their own change immediately, call `updateTag('product:<id>')` (Server Actions only).
- Elsewhere (Route Handlers, webhooks), call `revalidateTag(tag, 'max')`; the single-argument form is deprecated.
- `revalidatePath('/products')` remains available when the affected data is scoped to a path rather than a tag.
```ts
// app/products/actions.ts
'use server'
import { updateTag } from 'next/cache'
import { db } from '@/lib/db'
export async function renameProduct(id: string, name: string) {
// Authenticate and authorize here before writing.
await db.product.update({ where: { id }, data: { name } })
updateTag(`product:${id}`)
}
```
## Static params
- `generateStaticParams` lists params to prerender at build time. With Cache Components it must return at least one entry; an empty array is a build error.
- Without Cache Components, return an empty array (or use the previous model's options) to render paths on first visit.
## Verify before finishing
- `npx next build` succeeds and its route summary shows the rendering mode you intended for each changed route.
- In the dev overlay, no "blocking route" insight for the pages you changed.
- After a mutation, the edited value appears on the next request (for `updateTag`) or after background revalidation (for `revalidateTag(tag, 'max')`).
- `grep -rn "unstable_cache" app lib` returns no new uses.
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.