Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable cache for getServerSideProps?

We have few pages and components as server side rendering.

We were trying to use cache for few API responses.

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

Next.js version is 11.1.

Here can someone please suggest how can we implement cache?

like image 288
jpk Avatar asked Aug 28 '26 13:08

jpk


1 Answers

You can set the Cache-Control header inside 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
        }
    }
}

Setting a Cache-Control value only works in production mode, as the header will be overwritten in development mode.

See Caching with Server-Side Rendering documentation for more details.

like image 81
juliomalves Avatar answered Aug 30 '26 03:08

juliomalves