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