如何为 getServerSideProps 启用缓存?

2023-12-31

我们有很少的页面和组件作为服务器端渲染。

我们尝试对少数 API 响应使用缓存。

export async function getServerSideProps(context) {
   const res = await getRequest(API.home)
   return {
     props: {
       "home": res?.data?.result
     },
   }
}

Next.js 版本是 11.1。

有人可以建议我们如何实现缓存吗?


您可以设置Cache-Control标题内getServerSideProps using res.setHeader.

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值仅适用于生产模式,因为标头将在开发模式下被覆盖。

See 使用服务器端渲染进行缓存 https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props#caching-with-server-side-rendering-ssr文档以获取更多详细信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 getServerSideProps 启用缓存? 的相关文章

随机推荐