When to use getStaticProps and getServerSide props in real world scenario

Viewed 680

Hello I am new to the Next.js, I know that in getStaticProps Next.js will pre-render this page at build time and in getServerSideProps Next.js will pre-render this page on each request using the data returned by getServerSideProps

But i want a example of when to use getStaticProps and getServerSideProps for website

1 Answers

With getServerSideProps (SSR) data is fetched at request time, so your page will have a higher Time to first byte (TTFB), but will always pre-render pages with fresh data.(can be use for dynamic content/it allows you to improve your SEO as in this method the data is rendered before it reaches the client.)

With Static Generation (SSG) The HTML is generated at build time and will be reused on each request, TTFB is slower and the page is usually faster, but you need to rebuild your app every time the data is updated (can be acceptable for a blog, but not for an e-commerce).

With Incremental Static Regeneration (ISG) static content can also be dynamic, the page will be rebuilt in the background with an interval-based HTTP request. You can specify how often pages are updated with a revalidate key inside getStaticProps, this works great with fallback : true and allows you to have (almost) always updated content.

When to use:

  1. getStaticProps: Any data that changes infrequently, particularly from a CMS. (Must be used with getStaticPaths if there's a dynamic route).

  2. revalidate: An easy add-on to getStaticProps if the data might change, and we're OK serving a cached version.

  3. getServerSideProps: Primarily useful with data that must be fetched on the server that changes frequently or depends on user authentication.When we want to fetch data that relates to the user's cookies/activity and is consequently not possible to cache.

Related