Different Data Fetching Techniques in NextJs

SSG vs SSR vs ISR

Different Data Fetching Techniques in NextJs

NextJs is a JavaScript framework build on top of React that supports Server Side Rendering out of the box.

React application build using create-react-app uses Client-Side-Rendering(CSR). CSR is not helpful if you need SEO for your web application. That's where NextJS comes into play, if you are building something that requires SEO, then NextJS is the way to go.

In this blog, we will discuss different data fetching techniques in NextJs.But before that let's understand the difference between CSR and SSR.

Client-Side Rendering(CSR) Vs Server-Side Rendering(SSR)

In Client Side Rendering browser receives a JavaScript bundle and it does all the processing and processes the Js file and loads all of your HTML into the site by injecting it into the document object model dynamically.

So, it takes a few seconds for client(browser) to paint the HTML pages and the screen will be blanked for those time, which is not good for SEO. Initial load time is slow for CSR.

But subsequent page visits will be significantly faster in CSR as all the pages are already fetched it does not have to make another server call when you navigate to other pages.

On the other hand, in Sever Side Rendering, the client will receive a fully rendered HTML page. Sever will build the HTML pages at build time(or request time) and send it to the client whenever requested. Initial load time will be significantly faster in case of SSR, hence you get an improved SEO for your pages. We will now see how NextJs helps us to use SSR with React.

NextJs offers different data-fetching techniques like SSG, SSR, ISR.We will discuss each one of them today in this blog.

Different data fetching techniques offered by NextJs

  • Static Site Generation(SSG)

  • Server-Side Rendering(SSR)

  • Incremental Static Regeneration (ISR)

SSG - Static Site Generation

Let say you are building a blog and all your blog posts are hosted on a third-party CMS.

For this use case, SSG is a perfect choice.

In SSG, NextJs uses pre-rendering, your blogs posts will be fetched at build time at the server-side, and pre-build HTML pages will be served to the client. Your website will be blazing fast as it is not making requests to the server each time user requests for the blogs and furthermore the generated HTML pages can be cached by a CDN for improved performance. ( Vercel does that by default with zero configuration)

// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

// This function gets called at build time on server-side.
// It won't be called on client-side.
export async function getStaticProps() {
  // Call an external API endpoint to get posts.
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

export default Blog

But if you publish a new blog, it won't reflect on the UI automatically. You have to re-build the site and deploy it again to reflect the latest blogs. That's one downside of SSG which comes as an expense for performance.

So, this method is not useful for dynamic data. This can be good for a static site like a portfolio site or a landing page.

SSR: Server-Side Rendering

If you are building a dynamic site, where data changes every minute/second, then you should use SSR.

In SSR, Next.js will pre-render this page on each request. On each request, actual database call will be made unlike SSG to get the latest data. So data will never be stale using this technique.

Time to first byte (TTFB) will be slower than SSG as the server has to make API call on each request and the pages can not be cached in this method.

If SEO is not important for you and you don’t need to pre-render the data, you can use Client-Side Rendering (CSR) to fetch data. You can show some loading state for the missing data and other static content of the page will be pre-rendered using SSG. On the client side, you can fetch the data and replace the loading state with actual data.

function Products({ products}) {
  return (
    <ul>
      {products.map((product) => (
        <li>{product.title}</li>
      ))}
    </ul>
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const products= await res.json()

  // Pass data to the page via props
  return { props: { products} }
}

export default Products

ISR - Incremental Static Regeneration

If you are dealing with dynamic data but still wants to take the benefit of SSG for performance gains, then ISR can be a great choice for you.

In ISR also HTML is generated at build time, but here we can pass a revalidate property that will make the data stale after the specified time, and NextJS will fetch the recent data in the background if a new request comes in, invalidate the cache and replace it with the new data.

ISR enables you to use Static Site Generation, without needing to rebuild the entire site for any new data.

function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

// This function gets called at build time on server-side.
// if revalidation is enabled and a new request comes in
// it will be called again
export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  return {
    props: {
      posts,
    },
    // Call this function again after every 10s 
   // if new request comes in
    revalidate: 50, // In seconds
  }
}

As you can see, we have added revalidate:50, which will make the data stale after every 50s and this method will run to get the latest data.

So, if you publish a new blog after you deploy the site, now you don't have to re-deploy it again, new blogs will be automatically fetched once the revalidate time is passed.

Thanks for reading. Do leave your feedback

LinkedIn Instagram