Note: This article was last updated on March 4, 2021 and may contain outdated information.
Next.js provides two primary data-fetching approaches beyond client-side methods. The getStaticProps function generates static HTML files and supports Incremental Static Regeneration through the revalidate parameter.
However, getServerSideProps becomes necessary when you need to access query parameters from the URI—useful for search functionality and pagination. While powerful, this method processes each request individually, resulting in noticeably slower performance compared to static pages.
Performance Solution
If you’re hosting on Vercel, you can implement the stale-while-revalidate cache strategy using a single line of code. This approach delivers behavior comparable to getStaticProps with revalidate.
Access the response object from context and set the appropriate Cache-Control header:
export async function getServerSideProps(context) {
const { res } = context;
res.setHeader('Cache-Control', `s-maxage=60, stale-while-revalidate`)
return {
props: {},
}
}
This example caches the page for 60 seconds before revalidation, making server-side rendered pages feel as responsive as static ones.
Important Caveat
This technique works best for content served identically to all users but fetched dynamically. For user-specific or highly dynamic content, this strategy is ineffective.