Next.js 13.4.3部署后新增Hygraph文章页面不更新求助
问题描述
使用Next.js 13.4.3的App Router开发博客网站,本地执行npm run build和npm run start后,向Hygraph无头CMS新增文章并调用API的GET请求,页面可正常更新显示新文章;但部署到服务器后,同样操作页面却不更新,调用API返回成功,尝试清理服务器缓存、重新部署均无效。
相关代码
page.tsx
import BlogCard from '@/components/blog/PostCard'; import styles from './blog.module.scss'; const hygraphContentApi = "URI HERE"; interface Post { title: string; createdAt: string; slug: string; shortDescription: string; author: { name: string; picture: { url: string; }; }; coverImage: { url: string; }; } const QUERY = ` query { posts { title createdAt shortDescription slug author { name picture { url } } coverImage { url } } } ` export default async function Home() { const response: { data: { posts: Post[]}} = await fetch(hygraphContentApi, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: QUERY, }) }).then(res => res.json()) const posts = [...response.data.posts].sort((a, b) => { const dateA: Date = new Date(a.createdAt); const dateB: Date = new Date(b.createdAt); return dateB.getTime() - dateA.getTime(); }); return ( <main> {posts ? ( <div className={styles.blogCardsContainer}> {posts.length > 0 ? ( posts.map((post) => ( <BlogCard key={post.slug} post={JSON.stringify(post)} /> )) ) : ( null )} </div> ) : <div className={styles.loading}>Loading...</div>} </main> ); };
route.tsx (API)
import { revalidatePath } from "next/cache"; import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest) { const url = new URL(req.url); const auth = url.searchParams.get('auth'); const path = url.searchParams.get('path') if(!path) return NextResponse.json({revalidated: false}, {status: 400}) if(!auth) return NextResponse.json({revalidated: false}, {status: 400}) if(auth != process.env.HYGRAPH_WEBHOOK_REVALIDATE_AUTHID) return NextResponse.json({revalidated: false}, {status: 401}) revalidatePath(path) return NextResponse.json({revalidated: true, message: 'OK'}, {status: 200}) }
解决方案
1. 调整fetch请求的缓存策略
Next.js App Router中,fetch默认会缓存请求结果(静态渲染场景下),导致页面无法主动拉取新内容。在fetch配置中添加缓存规则:
const response: { data: { posts: Post[]}} = await fetch(hygraphContentApi, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: QUERY, }), // 二选一配置: cache: 'no-store', // 完全禁用缓存,每次请求都拉取最新数据 // next: { revalidate: 60 } // 每60秒自动重新验证一次缓存 }).then(res => res.json())
2. 确保revalidatePath的路径匹配准确
调用重新验证API时,path参数必须与博客页面的路由完全一致,比如博客页面路由是/blog,则请求API时要传path=/blog,避免路径不匹配导致重新验证失效。
3. 强制页面动态渲染
如果需要页面每次请求都重新生成内容,可在page.tsx顶部添加动态渲染配置:
export const dynamic = 'force-dynamic';
4. 验证服务器执行逻辑
- 确认服务器上
HYGRAPH_WEBHOOK_REVALIDATE_AUTHID环境变量配置正确,确保revalidatePath代码逻辑被触发; - 可在API路由中添加日志,验证重新验证操作是否执行:
// 在route.tsx的revalidatePath前添加 console.log(`触发路径重新验证:${path}`); revalidatePath(path);
5. 检查服务器缓存层
若部署的服务器存在额外缓存层(如CDN、反向代理),需确保这些缓存层的规则与Next.js的重新验证机制对齐,或手动清理缓存层数据。
内容的提问来源于stack exchange,提问作者KubaZary
相关产品推荐
相关产品推荐

