Blog>
Snippets

Next.js SSR Caching with getServerSideProps

Show how to cache Server-Side Rendered (SSR) pages in Next.js by using getServerSideProps and a custom caching layer.
// An example of a simple memory-based cache implementation
const ssrCache = new Map();

export async function getServerSideProps(context) {
  const { req } = context;
  const cacheKey = req.url;

  // Check if we have cached the page
  if (ssrCache.has(cacheKey)) {
    // Retrieve the page from cache
    return ssrCache.get(cacheKey);
  }

  const data = await fetchData(); // Your data fetching logic here

  // Page props
  const pageProps = { props: { data } };

  // Cache the page
  ssrCache.set(cacheKey, pageProps);

  // Set a cache timeout to invalidate
  setTimeout(() => ssrCache.delete(cacheKey), 1000 * 60 * 5); // Cache for 5 minutes

  // Return the page props
  return pageProps;
}
This piece of code sets up a simple server-side memory cache. It checks if the URL requested by the user is already in the cache. If it is, it serves the cached content. If not, it fetches new data, caches it, and then serves it to the user. Cached content is set to invalidate after 5 minutes.
import { getServerSideProps } from './path-to-above-function';

function Page({ data }) {
  return (
    <div>
      <h1>Data from SSR</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default Page;
This is a Next.js page component that imports the getServerSideProps function from the provided path. It uses the props fetched from getServerSideProps to display data. The data is stringified and displayed in a preformatted block.
body {
  font-family: 'Arial', sans-serif;
}
div {
  margin: 0 auto;
  width: 80%;
}
h1 {
  color: #333;
}
pre {
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  padding: 20px;
}
This CSS provides basic styling to the page component. It defines the body font, centers the content div, styles the header, and applies formatting to the preformatted block to enhance the readability of the data displayed there.