Next.js 13对接WordPress:开发正常构建时服务端取数失败
问题描述
开发环境运行一切正常,但执行npm run build构建生产版本时失败,报错信息如下:
info - Collecting page data [ ] info - Generating static pages (0/5)DynamicServerError: Dynamic server usage: no-store fetch
推测问题出在服务端数据获取逻辑和缓存配置上。
相关代码
数据获取函数 getData()
const getData = async (query: string) => { try { const { data } = await fetch("MY ENDPOINT", { method: "POST", cache: "no-store", // 怀疑是这里的问题,但改成force-cache后开发环境无法正常工作 next: { revalidate: 1, }, headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: query, }), }).then((res) => res.json()); return data; } catch (error) { console.error(error); } }; export default getData;
GraphQL 查询语句
export const getPostBySlug = (slug: string) => { const getPost = ` query PostBySlug { postBy(slug: "${slug}") { id content(format: RENDERED) title date } } `; return getPost; };
组件中调用数据的方式
export default async function Post({ params: { post }, }: { params: { post: string }; }) { const { postBy } = await getData(getPostBySlug(post)); return ( <article> {* 内容部分...*} // 其余内容和问题无关 </article> ); }
解决方案
报错原因是cache: "no-store"会强制请求每次都走动态服务器,而Next.js在静态构建阶段无法处理依赖动态服务器的内容,导致构建失败。以下是几种可行的解决方法:
方案1:根据环境切换缓存策略
修改getData()函数,开发环境用no-store保证实时获取数据,生产环境用force-cache配合revalidate兼顾静态构建和数据新鲜度:
const getData = async (query: string) => { try { const { data } = await fetch("MY ENDPOINT", { method: "POST", cache: process.env.NODE_ENV === 'development' ? "no-store" : "force-cache", next: { revalidate: 1, // 生产环境每1秒重新验证数据 }, headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: query, }), }).then((res) => res.json()); return data; } catch (error) { console.error(error); } }; export default getData;
方案2:标记页面为动态生成(不推荐,影响性能)
如果业务确实需要每次请求都获取最新数据,可以在页面组件顶部添加dynamic = "force-dynamic",告诉Next.js这是动态页面,构建时不生成静态文件:
export const dynamic = "force-dynamic"; export default async function Post({ params: { post }, }: { params: { post: string }; }) { const { postBy } = await getData(getPostBySlug(post)); return ( <article> {* 内容部分...*} // 其余内容和问题无关 </article> ); }
方案3:统一使用next.revalidate管理缓存
Next.js中next.revalidate的优先级高于cache配置,可以直接去掉cache字段,让框架自动处理缓存策略,既能满足开发环境的实时性,又能支持静态构建:
const getData = async (query: string) => { try { const { data } = await fetch("MY ENDPOINT", { method: "POST", next: { revalidate: 1, }, headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: query, }), }).then((res) => res.json()); return data; } catch (error) { console.error(error); } }; export default getData;
内容的提问来源于stack exchange,提问作者Dom V
相关产品推荐
相关产品推荐

