如何为 getServerSideProps 启用缓存?

4
我们有一些页面和组件是在服务器端渲染的。
我们尝试为少数API响应使用缓存。
export async function getServerSideProps(context) {
   const res = await getRequest(API.home)
   return {
     props: {
       "home": res?.data?.result
     },
   }
}

Next.js版本是11.1。

这里有人可以建议如何实现缓存吗?

1个回答

15

您可以在getServerSideProps内使用res.setHeader设置Cache-Control头。

export async function getServerSideProps(context) {
    // Add whatever `Cache-Control` value you want here
    context.res.setHeader(
        'Cache-Control',
        'public, s-maxage=10, stale-while-revalidate=59'
    )
    const res = await getRequest(API.home)
    return {
        props: {
            home: res?.data?.result
        }
    }
}

在生产模式下设置Cache-Control值才有效,因为在开发模式下,该标头将被覆盖。

有关更多详细信息,请参见使用服务器端渲染进行缓存文档。


2
这正是我正在寻找的,但不幸的是它似乎只能与Vercel和其他边缘提供商一起使用。 :-( - Adam Shand
@AdamShand 的 s-maxage 用于 CDN 或代理,对于 Web 浏览器请使用 max-age。请注意内容被缓存的三个位置:浏览器、CDN 和代理。 - Takash Futada
我使用了这个代码来移除缓存,以获取新的数据而不是重新加载页面:context.res.setHeader("Cache-Control","no-cache, no-store, max-age=0, must-revalidate"); - Shaze
如果设置了缓存,这是否意味着在缓存时间内,getServerSideProps 中的任何代码都不会运行? - alexr89
1
@alexr89 Cache-Control 头部由浏览器/CDN 使用。如果在缓存时间内,对 Next.js 服务器的请求甚至不会发生 - 缓存版本将被提供。因此,是的 - getServerSideProps 中的任何代码都不会针对该特定请求运行。 - juliomalves
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接