Skip to content

How to Choose Between Data Fetching Options in Next.js

A few days ago, we published another blog post related to Next.js: Understanding Next.js Data Fetching for Beginners.

In that blog post, we show the functions this framework provides us to perform different data fetching options. I hope you already have a basic understanding of Next.js. If not, I highly recommend that you first read the article linked above.

Let's get started.

There are multiple strategies for us to choose from, and it gets confusing at first to apply the correct solution in the correct place. We will take a real-life application, and understand which strategy works best for which scenarios.

The special functions that are used for pre-rendering in Next.js are:

  • getStaticProps
  • getStaticPaths
  • getServerSideProps

We will see in which scenarios you can apply these functions, and learn the best practices for doing so.

We are talking about an Online Store

Let's assume that we want to build an Online Store to display some products, a product page (and details), and an accounts page (order details, personal info, etc). Let's also assume that we don't want to use React because we want to optimize SEO.

Let's start thinking about this.

Landing Page (getStaticProps)

The landing of our OnlineStore is where you can see two things, the list of some products you want to highlight could be:

  • Featured Products
  • Popular products
  • Discounted Products
  • Upcoming Products

Whatever the case, the main thing is you already know which API you will be using, and probably that API will not change in the short term. In these scenarios, only getStaticProps is enough.

As we see in our previous post:

export async function getStaticProps() {
    const url = 'https://our-api-products.com/';
    const res = await fetch(url, {
        headers: {
        Accept: 'application/json',
        },
    });
    const data = await res.json();

    return {
        props: {
            products: data.products,
        },
    };
}

Now, our landing page will be pre-generated ahead of time and won't change. For further details and a breakdown of the getStaticProps method let's check our previous post getStaticProps.

Landing Page, but dynamic (getStaticProps + revalidate).

What happens if the landing page you are building is frequently changing the products based on user preferences? Then, you don't want to show the same page all the time.

In that case, you need to make sure that the generated pages will be updated at a regular interval.

With that in mind, you have to use the revalidate property. This property is defined in seconds to indicate the refresh interval.

export async function getStaticProps() {
    const url = 'https://our-api-products.com/';
    const res = await fetch(url, {
        headers: {
        Accept: 'application/json',
        },
    });
    const data = await res.json();

    return {
        props: {
            products: data.products,
        },
        revalidate: 20
    };
}

We gave our revalidate property the value of 20. It means we are still pre-generating our landing page, but it will be updated every 10 seconds. As we see in our previous post, this is called Incremental Static Regeneration.

Product detail (getStaticPaths)

Now, if for example, our customers click on one product, we have to show a details page of the product. We're calling a PI, like the product/?id=678.

What is interesting here, is we don't know which id we are looking for. So our server needs to know all of the valid ids ahead of time.

This is where getStaticPaths comes in. It tells the server all the available routes that we need to pre-generate.

export async function getStaticPaths() {
    const idList = getproducts().map(product => product.id)
    const params = idList.map(id => ({params: {productId: id}}))

    return {
        fallback: false,
        paths: params,
    };
}

export async function getStaticProps(context: GetStaticPropsContext) {
    const {params: { productId }} = context
    const productDetails = await getProductDetails(productId);

    return {
        props: { productDetails, }
    };
}

Now, only the pages with a valid id will be pre-generated.

Accounts Details (getServerSideProps)

Now, what if our customer wants to see her last purchases, or change her address or other personal info? After that, we need to validate some things.

Or, we want to make sure that the user has the right permissions to view the page. In these scenarios, we use getServerSideProps.

If you remember, in our previous post we talk about getServerSideProps, this option will not pre-generate any page. Instead, it will run the code inside the method every time the page is requested. Therefore this is more secure, but unfortunately less efficient.

export async function getServerSideProps() {
  const url = 'https://our-api-products.com/';
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const data = await res.json();

  return {
    props: {
      products: data.products,
    },
  };
}

Conclusion

That's it. First, we saw different data-fetching options. Now, we see how to choose between them, in real-life scenarios probably we are facing every day.

Now you should have a little understanding of how we can use NextJS for improved performance and SEO-Friendly in your application.

So far, we learned:

  • If we had a page in which the content will be the same and will remain the same for a long time, it's better to use getStaticProps.

  • If we need a page whose content will be dynamic based on some conditions, it's better to use getStaticProps with a revalidating option.

  • On the other hand, if we want to build a page and be sure that the id items are all valid, it's more likely to use getStaticPaths.

  • But, if we need to make a secure but dynamic page, we will definitely need getServerSideProps.