Search code examples
javascriptreactjsnext.jsserver-side-rendering

What exactly is different between getStaticProps + fallback:true and getServerSideProps?


I read Next.js documentation many times, but I still have no idea what's the difference between getStaticProps using fallback:true and getServerSideProps.

As far as I understand :

getStaticProps

getStaticProps is rendered at the build time and serves any requests as static HTML files. It is using with pages that are not updated often, for example, an About us page.

export async function getStaticPaths() {

return {
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }]
  }
}

But if we put fallback:true at the return of the function, and there is a request to the page that is not generated at the build time, Next.js will generate the page as a static page then other requests on this page will be served as a static.

export async function getStaticPaths() {

return {
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    fallback: true,
  }
}

So, getStaticProps's concept is working great for me. I think it can work for most scenarios. But if getStaticProps is working great, then why do we need getServerSideProps?

I understand that Next.js will pre-render each request if we use getServerSideProps. But why do we need it, when we can use getStaticProps to get the newest data, which I think it is better for TTPB?

Can you guys please explain it to me or guide me to something that can help me totally understand this?


Solution

  • Consider a web crawler that does not run Javascript, when it visits a page that was not built at build time, and its fallback is set to be true, Next.js will serve a fallback version of the page that you defined (Fallback pages). The crawler may see something like <div>Loading</div>.

    Meanwhile, if the crawler visits a page with getServerSideProps, Next.js will always respond with a page with all the data ready, so the crawler will always get the completed version of the page.

    From a user standpoint, the difference is not significant. In fact, the page with getStaticProps and fallback: true may even result in a better perceived performance.

    Also, as more and more crawlers execute JavaScript before indexing JavaScript, I would expect there will be fewer reasons to use getServerSideProps in the future.