How do you cache a nextjs page that has getServerSideProps?

2.3k views Asked by At

pages/stuff.ts

export function getServerSideProps(context) {
  const userId = getUserIdOrNull(context);
  return {props: { somethingComplicated: getSomethingComplicated(!!userId) }};
}
export default Home({somethingComplicated}) {
  return <div>{somethingComplicated}</div>
}

How do you cache this page?!

Ideally I'd like to cache the page <Home {...{somethingComplicated}}/> based on the different contexts.

Possible but unsatisfying solutions:

  • Cache the calculation of somethingComplicated. Unsatisfying because Home would need to be recalculated every time and cannot be cached by cloudflare.

  • Load somethingComplicated dynamically on the client from an api. Unsatisfying because the lack of server side rendering is a worse user experience.

  • Route for logged in users and logged out users to different routes. Unsatisfying because user visible urls will be different and the redirects get complicated.

I can't seem to find a satisfying solution. Maybe it's not possible? Anyways, thanks in advance for your time.

1

There are 1 answers

6
Yilmaz On

By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. Pre-rendering can result in better performance and SEO.

Each generated HTML is associated with minimal JavaScript code necessary for that page. When a page is loaded by the browser, its JavaScript code runs and makes the page fully interactive. (This process is called hydration.)

Two forms of Pre-rendering:

Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page.

Static Generation (Recommended): The HTML is generated at build time and will be reused on each request. Server-side Rendering: The HTML is generated on each request.

you can read more

If you are using getServerSideProps that means every time a user visits that page, you want to fetch fresh data and serve it to the user. If your serverside is doing heavy calculation or hitting database disk you could implement caching layer between application server and db or other servers. You could use redis