Next.js: How to build pages at request time and save it?

Viewed 57

I am currently using getStaticProps and getStaticPaths to build static HTML files but the issue is that every time it builds it builds around 10k+ pages. I do not know how to save getServerSideProps's built page, according to the docs it says it builds it at request time which is what I want but it doesn't mention anything about saving it like getStaticProps.

1 Answers

You cannot "turn" getStaticProps aka SSR-Pages into static pages, but you can achieve pretty much the same effect/speed by caching your API requests that the page requires in order to be built.

If you host on Vercel, you can do something like this:

res.setHeader("Cache-Control", "s-maxage=60, stale-while-revalidate=59")

From the docs:

This tells our CDN the value is fresh for one second. If a request is repeated within the next second, the previously cached value is still fresh. The header x-vercel-cache present in the response will show the value HIT. If the request is repeated between 1 and 60 seconds later, the cached value will be stale but still render. In the background, a revalidation request will be made to populate the cache with a fresh value. x-vercel-cache will have the value STALE until the cache is refreshed.

If your content never changes, you can remove stale-while-revalidate and set s-max-age very high, so that the response stays cached until your next re-deploy:

export async function getServerSideProps({ res }) {
  res.setHeader('Cache-Control', 's-max-age=10000000000')
  return {
    props: {
    }
  };
}

Source: https://vercel.com/docs/concepts/edge-network/caching

Related