Next.js 15 Fullstack (App Router + Server Actions) · 课时

退出缓存:动态渲染与 no-store

在缓存不合适时,使用 Cookie、请求头和 no-store 指令强制动态行为。

第 4 / 4 课13 个步骤

退出缓存:动态渲染与 no-store 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

When Caching Is Wrong

By default, Next.js 15 tries to make your routes static at build time and cache data aggressively. That is great for marketing pages, but wrong for things that must reflect the current request.

  • A dashboard showing the logged-in user's data
  • A page that reads the request's cookies() or headers()
  • Prices, inventory, or notifications that change every second

This lesson is about opting out of caching: forcing dynamic rendering and disabling fetch caching with no-store.

Static vs Dynamic Rendering

A route is rendered in one of two modes:

  • Static: rendered once (at build, or in the background) and the HTML/data is reused for everyone.
  • Dynamic: rendered fresh on every request, so it can read per-request input.

Next.js decides automatically. The moment your code touches a Dynamic API (cookies(), headers(), searchParams) or an uncached fetch, the route switches to dynamic. You rarely flip it manually — you opt out of caching and the renderer follows.

cookies() Forces Dynamic

Reading cookies() inside a Server Component signals that the output depends on the incoming request. In Next.js 15 these APIs are async — you must await them.

Touching cookies() at all moves the route to dynamic rendering. There is no way to read a cookie statically, because a static page has no request to read from.

import { cookies } from 'next/headers';

export default async function DashboardPage() {
  const cookieStore = await cookies();
  const theme = cookieStore.get('theme')?.value ?? 'light';

  // Reading cookies() opts this page out of static rendering
  return <main data-theme={theme}>Welcome back</main>;
}

headers() Forces Dynamic Too

Like cookies, headers() is async in Next.js 15 and reading it forces dynamic rendering. Use it when output depends on request headers such as Authorization, User-Agent, or a geo header from your CDN.

Because the header value is per-request, the page can never be cached as a single static HTML for all users.

import { headers } from 'next/headers';

export default async function GreetingPage() {
  const headerList = await headers();
  const country = headerList.get('x-vercel-ip-country') ?? 'unknown';

  return <h1>Hello from {country}</h1>;
}

fetch with cache: 'no-store'

Next.js extends the native fetch with caching options. By default a fetch result may be cached, which is wrong for always-fresh data.

Pass cache: 'no-store' to bypass the cache entirely. Every render performs a real network request, and the route becomes dynamic.

  • cache: 'no-store' → never cache, always refetch
  • cache: 'force-cache' → cache indefinitely (the old default)
async function getLivePrice(symbol: string) {
  const res = await fetch(`https://api.example.com/price/${symbol}`, {
    cache: 'no-store',
  });
  return res.json() as Promise<{ price: number }>;
}

export default async function PricePage() {
  const { price } = await getLivePrice('BTC');
  return <p>Current price: {price}</p>;
}

next: { revalidate: 0 } Is the Same

There are two equivalent ways to disable caching on a single fetch:

  • { cache: 'no-store' }
  • { next: { revalidate: 0 } }

Both mean "do not serve this from cache." Prefer cache: 'no-store' for readability. Do not combine cache: 'force-cache' with revalidate: 0 — those conflict, and Next.js will warn.

// These two calls behave identically
await fetch(url, { cache: 'no-store' });
await fetch(url, { next: { revalidate: 0 } });

Route Segment: dynamic = 'force-dynamic'

Instead of opting out per fetch, you can opt out for an entire route segment using the route segment config. Exporting dynamic = 'force-dynamic' from a page.tsx or layout.tsx forces every render to be dynamic and disables the data cache for that segment.

Use this when most data on the page must be fresh, so you do not have to annotate each fetch individually.

// app/feed/page.tsx
export const dynamic = 'force-dynamic';

export default async function FeedPage() {
  // No need for cache: 'no-store' on each fetch —
  // the whole segment is dynamic
  const res = await fetch('https://api.example.com/feed');
  const items = await res.json();
  return <ul>{items.map((i: { id: string; text: string }) => <li key={i.id}>{i.text}</li>)}</ul>;
}

fetchCache: 'default-no-store'

A subtler knob is fetchCache. Setting fetchCache = 'default-no-store' changes the default for every fetch in the segment to no-store, while still letting an individual fetch opt back in with cache: 'force-cache'.

This is handy for an authenticated area where almost everything is per-user, but a few public lookups can still be cached.

// app/(app)/layout.tsx
export const fetchCache = 'default-no-store';

// Now any plain fetch() in this segment defaults to no-store.
// Opt back in explicitly when you want caching:
// await fetch(url, { cache: 'force-cache' });

Dynamic APIs in Route Handlers

Route Handlers (route.ts) follow the same rules. A GET handler can be cached unless it reads a Dynamic API or you opt out.

Reading request.url search params, or calling cookies()/headers(), makes the handler dynamic. You can also force it with export const dynamic = 'force-dynamic'.

// app/api/me/route.ts
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

export async function GET() {
  const session = (await cookies()).get('session')?.value;
  if (!session) {
    return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
  }
  return NextResponse.json({ user: session });
}

Server Actions Are Always Dynamic

Server Actions run in response to a user interaction, so they are inherently dynamic — they are never statically cached. They read the cache and can invalidate it, but the action body itself always executes fresh.

After mutating data in an action, call revalidatePath or revalidateTag so cached pages refetch. The action does not need no-store itself.

'use server';
import { revalidatePath } from 'next/cache';

export async function addComment(postId: string, text: string) {
  await db.comment.create({ data: { postId, text } });
  // Force the post page to refetch its (otherwise cached) data
  revalidatePath(`/posts/${postId}`);
}

Don't Reach for no-store Too Early

Opting out of caching is a real performance cost: every request hits your origin and database. Before forcing dynamic everywhere, ask whether time-based revalidation would do.

  • Data fresh within a few seconds → next: { revalidate: 5 }
  • Data must reflect this exact request → no-store / dynamic
  • Data changes on a known event → cache + revalidateTag on mutation

Use no-store when correctness truly depends on per-request freshness — not as a reflex to "make it work."

Quick Check

Test your understanding of opting out of caching in Next.js 15.

Recap

You learned how to opt out of caching when it would be wrong:

  • Dynamic APIs — awaiting cookies() or headers() automatically forces dynamic rendering.
  • Per-fetch — cache: 'no-store' (or next: { revalidate: 0 }) skips the data cache.
  • Per-segment — export const dynamic = 'force-dynamic' makes the whole route dynamic; fetchCache = 'default-no-store' changes the default per fetch.
  • Route Handlers follow the same rules; Server Actions are always dynamic and invalidate caches with revalidatePath/revalidateTag.
  • Restraint — prefer time-based or tag-based revalidation; reach for no-store only when correctness needs per-request freshness.
免费开始

用 AI 导师学习 TypeScript — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
22
课程
88

常见问题解答

「退出缓存:动态渲染与 no-store」课时是免费的吗?

是的 — 「退出缓存:动态渲染与 no-store」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

「退出缓存:动态渲染与 no-store」这节课中我会学到什么?

在缓存不合适时,使用 Cookie、请求头和 no-store 指令强制动态行为。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「退出缓存:动态渲染与 no-store」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 四种缓存:请求、数据、完整路由与路由器
  2. 基于时间与按需重新验证的策略
  3. 基于标签的精细缓存失效
  4. 退出缓存:动态渲染与 no-store
← 返回 Next.js 15 Fullstack (App Router + Server Actions)