Improve getServerSideProps Performance on Next.js

Learn how to use stale-while-revalidate cache strategy to make server-side rendered pages feel as responsive as static ones.

Mutual
Written by
Mutual
Published 4 Mar 2021
1 min read

Next.js gives you two main server-side data-fetching options. getStaticProps builds static HTML at build time, and Incremental Static Regeneration (revalidate) refreshes it in the background.

getServerSideProps is the one you reach for when you need query parameters from the URL — search results, pagination, anything per-request. The downside is it runs on every request, so it's noticeably slower than static pages.

The fix on Vercel

On Vercel you can get getStaticProps-with-revalidate behaviour out of getServerSideProps by setting a stale-while-revalidate Cache-Control header. One line:

export async function getServerSideProps(context) {
  const { res } = context;
  res.setHeader('Cache-Control', `s-maxage=60, stale-while-revalidate`)
  return {
    props: {},
  }
}

Above: cache for 60 seconds, revalidate after. Server-rendered pages feel as quick as static ones.

Caveat

This only works for content that's the same for every visitor. For anything user-specific, it'll leak one user's data to the next — don't use it there.

Further reading

Craft CMS
GraphQL vs Element API for headless Craft CMS
6 min
AI
Your Site in the Age of AI
3 min
Site Launch
Site Launch: The Global Rights Index
1 min

Let's get your site
where it should be

Emma Andrew

Start a conversation with Emma and Andrew

Emma, Operations Director · Andrew, Technical Director

hello@mutual.agency