Skip to content

Improve getServerSideProps Performance on Next.js

Mutual
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.

More from the blog

Let's get your site
where it should be

Tell us a bit about your site and what it needs to do. We'll reply within a working day, and you'll be talking to the people who'd do the work.