Next.js 13 数据重验证失效求助:Sanity博客内容不更新
Next.js 13 + Sanity 博客缓存更新问题排查与解决
问题描述
- 开发服务器运行正常,生产环境(Vercel)下:
- 新增博客后,首页无法显示新内容
- 编辑旧博客标题,详情页标题更新,但首页未同步
- 首页与详情页调用同一
getBlogs函数获取数据,已设置revalidate:10,尝试no-store也无效
相关代码
获取数据函数 getBlogs
import { client } from "@/sanity/lib/client"; export default async function getBlogs() { const query = '*[_type == "post"]'; const data = await client.fetch(query, { next: {revalidate: 10 } }); if (!data) { throw new Error("Failed to fetch data"); } return data; }
首页代码片段
import getBlogs from "./utils/getBlogs"; export default async function Home() { const data = await getBlogs(); // ... 页面渲染逻辑 }
解决方法
调整缓存策略的配置位置
将页面级的重验证配置直接写在首页组件中,而非仅在数据函数里:import getBlogs from "./utils/getBlogs"; export const revalidate = 10; // 为整个首页设置重验证间隔 export default async function Home() { const data = await getBlogs(); // ... }同时修改
getBlogs函数,明确禁用Sanity客户端自身的缓存:const data = await client.fetch(query, {}, { cache: 'no-store', next: { revalidate: 10 } });验证Sanity查询结果
在Sanity Studio的Vision工具中执行*[_type == "post"],确认查询返回的是最新数据。如果结果正确,说明问题出在Next.js的缓存层。启用On-Demand Revalidation(按需重验证)
实现一个API路由来手动触发页面重验证:// app/api/revalidate/route.js import { revalidatePath } from 'next/cache'; import { NextResponse } from 'next/server'; export async function POST(request) { const path = request.nextUrl.searchParams.get('path'); if (!path) { return NextResponse.json({ message: 'Path is required' }, { status: 400 }); } revalidatePath(path); return NextResponse.json({ revalidated: true }); }然后在Sanity中配置Webhook,当
post类型文档创建或更新时,调用该API路由(传入path=/),自动触发首页的重验证。检查Vercel部署的缓存设置
Vercel可能对静态页面有额外缓存,可在Vercel控制台的项目设置中,检查"Cache Control"配置,确保没有覆盖Next.js的重验证规则。确认Next.js版本
升级到Next.js 13的最新稳定版,旧版本的App Router可能存在缓存逻辑的bug。
内容的提问来源于stack exchange,提问作者Anirudha Pratap Sah
相关产品推荐
相关产品推荐

