How to save data in state or cache in getServerSideProps?

Viewed 184

I am building a Next.js app it is supposed to be SSR. So I have some common data, e.g Navigation and a few other things which I do need to be server rendered and I need it on every page. But loading it on every page from my REST API in getServerSideProps when I move between pages doesn't seem right.

So I am looking for a way to save this information in some local cache or state and I don't load it the second time when I move to another page in the browser.

Is there a way to do so?

1 Answers

You can set the Cache-Control header inside getServerSideProps to cache its response.

Example from the Caching with Server-Side Rendering documentation:

// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously cached value will still be fresh. 
// If the request is repeated before 59 seconds, the cached value will be  
// stale but still render (stale-while-revalidate=59). 
// In the background, a revalidation request will be made to populate the 
// cache with a fresh value. If you refresh the page, you will see the new value. 
export async function getServerSideProps({ req, res }) {
    res.setHeader(
        'Cache-Control', 
        'public, s-maxage=10, stale-while-revalidate=59'
    )

    return { 
        props: {} 
    } 
} 

You can configure the Cache-Control header value as you see fit. Note that setting a Cache-Control value only works in production mode, as the header will be overwritten in development mode.

Related