Next.js 14生产环境中如何禁用服务器端数据获取缓存?
解决Next.js 14生产环境SSR页面数据缓存问题
你的问题核心是Next.js App Router默认对服务器端渲染的页面数据做了静态缓存,导致生产环境下数据更新后页面仍显示旧内容。以下是两种针对性的解决方案:
方案1:全局禁用页面静态缓存
在你的Page组件顶部添加dynamic配置,强制页面每次请求都重新渲染并获取最新数据:
export const dynamic = 'force-dynamic'; export default async function Page() { const magazines = await getMagazines(true); return ( <Box sx={{ display: "flex", flexDirection: "column", height: "100vh", }} > <ContextProvider> <Header /> <Content magazines={magazines} /> </ContextProvider> </Box> ); }
方案2:仅禁用特定数据请求的缓存
如果不想让整个页面都变为动态渲染,可在数据请求函数中添加缓存禁用指令,只针对杂志数据的查询跳过缓存:
import { unstable_noStore as noStore } from 'next/cache'; export async function getMagazines( includeUnpublished: boolean = false ): Promise<Magazine[] | null> { noStore(); // 禁用当前函数的缓存 const magazines = await prisma.magazine.findMany({ where: includeUnpublished ? {} : { isPublished: true }, orderBy: [ { year: "desc", }, { number: "desc", }, ], }); return magazines || null; }
两种方案的区别
force-dynamic:整个页面变为动态渲染,每次请求都会重新执行Page组件内的所有逻辑,适合需要完全实时的页面。noStore:仅对单个数据请求禁用缓存,页面其他部分仍可享受Next.js的静态优化,适合大部分需要实时数据但页面结构相对稳定的场景。
内容的提问来源于stack exchange,提问作者monty.py
相关产品推荐
相关产品推荐

