如何为 getServerSideProps 启用缓存?

How to enable cache for getServerSideProps?

我们有几个页面和组件作为服务端渲染。

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

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

Next.js 版本为 11.1.

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

您可以使用 res.setHeadergetServerSideProps 中设置 Cache-Control header。

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
        }
    }
}