如何在Vercel上使用Astro避免缓存响应?
Astro客户端获取数据在Vercel上持续返回缓存响应
我在Astro项目中通过客户端请求/api/spotify端点获取Spotify数据,本地开发环境下能正常拿到最新数据,但部署到Vercel后,客户端一直收到缓存的旧响应。
相关代码与配置
1. API端点代码 (src/pages/api/spotify.ts)
我已经禁用了预渲染,并设置了Cache-Control头:
export const prerender = false; ... export const GET: APIRoute = async () => { ... return new Response( JSON.stringify({ currentlyPlaying: currentlyPlayingTrack && formatTrack(currentlyPlayingTrack), topTracks: userTop.items.map(formatTrack), } satisfies APIResponse), { headers: { "Cache-Control": "public, s-maxage=60, stale-while-revalidate=30", }, }, ); };
2. 页面加载客户端组件 (src/pages/index.astro)
使用client:load确保组件在客户端渲染:
<SpotifyTrackList client:load />
3. React组件与数据获取
通过nanostores/query创建数据获取store:
// SpotifyTrackList.tsx export function SpotifyTrackList() { const { data } = useStore($spotifyData); return ( <> {data?.currentlyPlaying && ( // 剩余代码省略
// 数据存储定义 import { nanoquery } from "@nanostores/query"; export const [createFetcherStore, createMutatorStore] = nanoquery({ fetcher: (...keys: Array<string | number | true>) => fetch(keys.join("")).then((r) => r.json()), }); export const $spotifyData = createFetcherStore<APIResponse>(["/api/spotify"]);
4. Astro配置 (astro.config.ts)
使用hybrid输出模式和Vercel适配器:
output: "hybrid", adapter: vercel({ webAnalytics: { enabled: true, }, imageService: true, }),
尝试过的解决方法
我添加了vercel.json来强制设置API端点的缓存头,但问题依旧:
{ "headers": [ { "source": "/api/spotify", "headers": [ { "key": "Cache-Control", "value": "public, s-maxage=60, stale-while-revalidate=30" } ] } ] }
响应头信息(未添加vercel.json时)
检查响应头发现Vercel返回了缓存命中,且Cache-Control头被覆盖为public, max-age=0, must-revalidate:
HTTP/2 304 cache-control: public, max-age=0, must-revalidate date: Fri, 05 Jul 2024 18:30:55 GMT server: Vercel x-vercel-cache: HIT x-vercel-id: fra1::9k9pw-1720204255073-11f1e9dc8577 X-Firefox-Spdy: h2
求解决方案
如何让Vercel正确遵循我设置的缓存策略,确保客户端能定期获取最新数据?
内容的提问来源于stack exchange,提问作者user26121356
相关产品推荐
相关产品推荐

