Data Fetching in NextJS

Data Fetching in NextJS

Introduction

In today's digital world, websites, and web applications have become essential to our lives. With the increasing demand for fast and responsive web experiences, developers are always exploring new ways to enhance website performance. NextJS, a popular React-based framework, has gained immense popularity for its ability to create fast and SEO-friendly websites.

One of the critical features of NextJS is its data fetching capabilities, which allow developers to retrieve data from various sources and display it on the website. With the right implementation of data fetching in NextJS, you can provide users with fast-loading and dynamic web pages, leading to a better user experience.

In this blog, we'll take a closer look at the data-fetching features in NextJS and explore the best practices for implementing them. By the end of this blog, you'll understand how to leverage data fetching in NextJS to create high-performing and SEO-friendly websites. So let's dive in!

Data in an application can be Static(or Not Frequently Changing) and Dynamic. NextJS provides two methods to fetch these data and improve the application's performance depending on the type of Data to be displayed. These methods are:

  • getStaticProps

  • getServerSideProps

Let us individually dig deep into both these methods.

Using getStaticProps:

getStaticProps is a built-in method by NextJs to fetch data during the build of the application. This means that getStaticProps only runs when the application is getting built. The data that is fetched inside this method is stored on the Page as JSON static file. Even if the data at the source changes, it won't be reflected on the webpage till the application is built again. As the page and the data are stored on the server as a pre-rendered JSON file, it provides a great user experience with a faster load time for the page.
Now, since the data is Static on such a webpage how to deal when there is a change in the data source? There are two ways to update your data:

  • Set up systems to regularly rebuild the application so that getStaticData executes again and update data can be stored on the page. This way is useful when multiple pages are required to be rebuilt as the entire application is built again.

If you don't want to build the entire application again, you can make use of revalidate option to serve your user with updated data.

How does using revalidate option solve our problem?

Revalidate is an option used to specify the time in seconds after which the page must be regenerated. NextJS uses a caching mechanism to store previously generated pages. When the page is requested, it will serve the user with this cached page. If we use revalidate option, every time the page is requested by the user, it will compare whether the mentioned amount of time has passed or not since the page was last generated. If the time has not passed then NextJS will serve this cached page and if the time has passed it will regenerate the page, which will again run getStaticProps and new data will be fetched. The page with new data is served to the user and also cached by NextJS.

// Here I will show you how to use `getStaticProps` in your application.

// This is a page inside nextJS application.

function home({data}) {
    //destructing props object to get `data` sent from getStaticProps
    console.log(data);
    return (
        <h2>Fetching data inside getStaticProps</h2>
    )
}

// making getStaticProps function async is optional
export async function getStaticProps(){
    const res = await import(/data/data.json);
    const json = await res.json();

    return {
        props: {
            data: json,
        }
    }
}

Using getServerSideProps:

getServerSideProps is a built-in method by NextJS. This method is executed when the page is requested by the user. When a page using getServerSideProps is requested by the user, this method executes on the server to fetch the data. Once the data is fetched, the data is passed to the page via props object. The data is rendered on the page and sent to the user.

  • If the page is directly requested from the user, the server will execute getServerSideProps and then send the page to the user.

  • If the page is requested due to internal routing of the application, NextJS will send an api request to the server and execute this method. The props are in the response of this api call.

As the method is executed everytime the page is requested from the server, the data returned by this method is always up to date.

// Here I will show you how to use `getServerSideProps` in your application.

// This is a page inside nextJS application.

function home({data}) {
    //destructing props object to get `data` sent from getServerSideProps
    console.log(data);
    return (
        <h2>Fetching data inside getServerSideProps</h2>
    )
}

// making getServerSideProps function async is optional
export async function getServerSideProps(){
    const res = await import(/data/data.json);
    const json = await res.json();

    return {
        props: {
            data: json,
        }
    }
}

Rules for using getServerSideProps and getStaticProps:

There are certain rules to be followed while using getStaticProps or getServerSideProps:

  • These methods only work as expected when they are used inside a page file and not inside non-page files like components

  • These methods must be used as stand-alone functions and not inside any other functions.

  • Functions must be exported from the page file

  • getStaticProps and getServerSideProps cannot be used together in the same page.

Conclusion:

Whether you should use getStaticProps or getServerSideProps entirely depends on your specific use case. One important thing is considered while selecting either of the two methods is considering how frequently your data changes and do you need to always show up to date data or no. Depending on these parameters you can select getStaticProps or getServerSideProps.

I hope you found this article useful and easy to understand. Please share it more so even others can gain benefits from it.

You can connect with me using below links!

Github

Twitter

Linkedin

Thankyou, for your precious time.