Improve getServerSideProps Performance on Next.js
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
Protecting Craft CMS with Cloudflare
Why you should protect your Craft CMS site with Cloudflare, and how to set it up.
Craft CMS and PHP2Shell - how we dealt with it
How Mutual (a Craft CMS agency) handled the PHP2Shell vulnerability.
What's happened to my ChatGPT traffic?
You might have seen a drop in traffic from ChatGPT from this week. Here's what's happening...