Improve getServerSideProps performance on Next.js
Next.js has two main ways for data fetching, other than doing it on the client-side…
getStaticProps
is our go-to option, and builds the page as a static HTML file, and then using revalidate
you can take advantage of Incremental Static Regeneration
But sometimes you want to use getServerSideProps
, which unlocks additional functionality such as being able to access query parameters in the URI. This is useful for things like search engines and paginated pages. But the moment you use getServerSideProps
you will notice that it feels slow compared to a static page. This is because every time the page is requested it has to be processed before being served.
Fortunately, if you use Vercel to host your frontend, with one line of code you can take advantage of the stale-while-revalidate
cache strategy which has very similar (perhaps even identical) behaviour to getStaticProps
when using revalidate
.
To do this, you access the res
(response) variable from context
, and then set a Cache-Control
header.
In this example, the page is set to revalidate after 60 seconds…
export async function getServerSideProps(context) {const { res } = context;res.setHeader('Cache-Control', `s-maxage=60, stale-while-revalidate`)return {props: {},}}
… and now your getServerSideProps
pages will feel speedy like your getStaticProps
pages.
Note: if you're using getServerSideProps
because you are loading in content that's very dynamic (such as user-specific content) this technique almost certainly won't work for you. But if all users get the same content, it's just fetched in a very dynamic way, this is an effective technique.