Next.js 16 缓存解释:重新验证、标签、草稿模式与真实生产模式

发布: (2026年2月22日 GMT+8 18:12)
5 分钟阅读
原文: Dev.to

Source: Dev.to

🎯 我们正在构建的内容

一个可用于生产环境的缓存思维模型:

  • 使用 fetch 实现静态 + 动态控制
  • 基于标签的失效机制
  • 按需重新验证
  • 用于预览工作流的草稿模式
  • 我实际使用的真实场景

无需猜测。避免意外的陈旧页面。

🧠 首先:全新的思维模型

在 Next.js 16 中,缓存不再是“基于页面”的。
它是 基于数据 的。缓存的单位现在是 fetch() 调用。

  • 每个 fetch 都可以是缓存的或动态的。
  • 每个 fetch 都可以定义重新验证规则。
  • 每个 fetch 都可以通过标签进行失效。

这样更简洁,也更具可扩展性。

🔥 1. 使用 fetch 控制缓存

默认行为

const res = await fetch("https://api.example.com/posts");

默认情况下,此响应在生产环境中会被缓存。

静态并重新验证(ISR 风格)

const res = await fetch("https://api.example.com/posts", {
  next: { revalidate: 60 }
});
  • 缓存此响应。
  • 每 60 秒重新验证一次。

用更细粒度的方式取代旧的 ISR 模式。

完全动态(无缓存)

const res = await fetch("https://api.example.com/posts", {
  cache: "no-store"
});

强制动态渲染。适用于以下情况:

  • 用户特定数据
  • 已认证的仪表盘
  • 快速变化的指标

🏷️ 2. 真正的升级:缓存标签

Next.js 16 允许你为缓存的 fetch 添加标签:

const res = await fetch("https://api.example.com/posts", {
  next: { tags: ["posts"] }
});

现在,缓存条目与 "posts" 标签关联,可实现手动失效。

🚀 3. 按需标签重新验证

创建一个重新验证标签的路由处理程序:

// app/api/revalidate/route.ts
import { revalidateTag } from "next/cache";

export async function POST() {
  revalidateTag("posts");
  return Response.json({ revalidated: true });
}

调用此端点会立即使所有标记为 "posts" 的缓存请求失效——精准的、非页面级别的、也不是全局的。

🧪 4. 结合重新验证 + 标签(最佳模式)

const res = await fetch("https://api.example.com/posts", {
  next: {
    revalidate: 3600,
    tags: ["posts"]
  }
});
  • 自动每小时刷新
  • 需要时手动失效
  • 没有不必要的重建

📝 5. Draft Mode for Preview Workflows

启用草稿模式

import { draftMode } from "next/headers";

export async function GET() {
  draftMode().enable();
  return Response.redirect("/admin");
}

在页面中使用草稿模式

import { draftMode } from "next/headers";

export default async function Page() {
  const { isEnabled } = draftMode();

  const res = await fetch("https://api.example.com/posts", {
    cache: isEnabled ? "no-store" : "force-cache"
  });

  const data = await res.json();

  return { data.title };
}

当草稿模式激活时:

  • 缓存被绕过
  • 未发布的更改可见

关闭时,恢复正常缓存。

⚙️ 6. 实际使用的生产模式

用例缓存配置
公共内容next: { revalidate: 600, tags: ["posts"] }
管理员更新revalidateTag("posts")
用户仪表盘cache: "no-store"
预览路由draftMode + no-store

结果:性能、新鲜度、精确性、可扩展性。

⚠️ 常见错误

  • cache: "no-store"revalidate 混用
  • 忘记标签并尝试重新验证整个路径
  • 认为开发模式会反映生产缓存
  • 过度失效

提示: 开发模式行为不同。始终在生产构建中测试缓存:

next build
next start

🧩 这如何改变一切

在 Next.js 16 之前,缓存感觉是基于页面且间接的。
现在它是:

  • 声明式
  • 细粒度
  • 完全可控

从页面 ISR 转向 fetch 级别缓存是一次重大的架构改进。

🏁 最后思考

Next.js 16 不仅提升了缓存——它让缓存变得可预测。
如果你了解:

  • fetch 缓存控制
  • revalidate
  • tags
  • revalidateTag()
  • draftMode()

就能掌控性能,而不是盲目猜测。

如果这让你更清晰了,欢迎分享给其他正在与陈旧数据作斗争的前端工程师。
我很想看到你在 Next.js 16 中构建的任何有趣的缓存模式。

更多深度解析即将推出。

Check me out at .

0 浏览
Back to Blog

相关文章

阅读更多 »