DEV Community

Cover image for Data Fetching in Next.js
Anurag Gharat
Anurag Gharat

Posted on • Updated on

Data Fetching in Next.js

If you have been using React.js you should be familiar with Client Side Rendering(CSR). To explain it in short, CSR is when the Site is built and assembled on the Client Side. So the entire App is loaded and rendered in the Client Side which is the browser. Data fetching takes place in the browser itself. Since React only supports CSR, it has some limitations. Here comes Next.js.

Next.js is a React Framework for creating Server Side Rendered Apps.

Next.js provides 4 different ways to Fetch data.

  1. Data Fetching during build time - Static Site Generation (SSG)
  2. Data Fetching during request time - Server Side Rendering (SSR)
  3. Data Fetching based on condition - Incremental Site Regeneration (ISR)
  4. Data Fetching on Client side - Client Side Rendering (CSR).

Before we start I have already created a Demo of data fetching in Next.js. You can check it here

https://data-fetching-in-next-js-1za1z1g0g-anuraggharat.vercel.app/.

Static Site Generation (SSG):

This is also called as Build time data fetching. Here we fetch the data at the Build time of the site and add it to the page. Hence we get a page which is already loaded with data. For performing build time data fetching we use getStaticProps() method. During the build process of the website, the data is fetched by the getStaticProps() method and passed onto the page. Using this data the page is completely built and then served statically. The page will not be build again until a new build is triggered. So the data won’t be refreshed and updated. getStaticProps()runs at build time only. The end result here is a static site generated at build time which is ready to be served.

Code Example:

//Export this function under your page which you want to render statically
export async function getStaticProps(context) {
  //Make API call here 
    const res = await fetch(`your API url`);
    const data = await res.json();
  return {
    props: { data }, // will be passed to the page component as props
  };
}
Enter fullscreen mode Exit fullscreen mode

Benefits:

  1. Fast load time since the page is already generated.
  2. Better SEO since the contents of page is available even before the user requests.
  3. Can be used for Static Side Generation.

When to Use?

  1. When you want the data to be ready before the user requests it.
  2. When the content is not going to change.
  3. When SEO and Performance is the top most priority for that page.
  4. When the data is available at Build Time.

Use Case:

Consider you are building a portfolio website that renders markdown blogs at build time. In such case you can use getStaticProps() to read the blogs and create a Blog page on build time. So next time when you add a new blog, the website is built again and new blogs are shown.

You can combine getStaticProps with getStaticPaths to create pages for dynamics routes. For example. Lets say you have a blog page on URL “yoursite.com/blog” which lists down all the blogs and a specific blog page “yoursite.com/blog/name-of-blog” which is a dynamic route which shows a specific blog. In such case you can use these two functions to create all the dynamic paths at build time, create pages for it using getStaticPaths and fill it with content using getStaticProps . All this on build time. So in the end what you have is a website with several Static pages corresponding to each individual blog. My personal portfolio uses this approach.

Refer this demo for understanding about Static Props and Static Paths.

https://data-fetching-in-next-js-1za1z1g0g-anuraggharat.vercel.app/

Server Side Rendering (SSR):

Use getServerSideProps() to fetch data on Server on each user request. This function fetches data on every user request on the server. A user requests a page, the server finds a page for that URL, builds it by fetching data and returns back the page. Since the page uses server side rendering, the data is fetched at the server and data is passed as props to the page .Page accepts the props and is built on the server and then returned back. So for every new request, page is built again. Since a completely assembled page is returned the users can directly start interacting with it. getServerSideProps()runs on each request on the server side only.

Example code:

//Export this function under your page which you want to render on server
export async function getServerSideProps(context) {
  //make your API request here
    const res = await fetch(`your API Url`)
  const data = await res.json()

  return {
    props: {}, // will be passed to the page component as props
  }
}
Enter fullscreen mode Exit fullscreen mode

Benefits:

  1. The page is available for user interaction instantly.
  2. The page remains updated because the page is built on every request.
  3. Great for SEO.

When to use:

  1. When you wish to show a page which has data that is updated frequently.
  2. When you want the data to be available to user as soon as the page loads.

Use Case:

Lets say you are creating a E Commerce website. On Shopping page the content gets updated every day based on inventory. Hence you could use Server Side Fetching Method which builds the page every time a user requests it. The user will be served with a page with the most up to date content.

Incremental Site Regeneration:

This is a combination of Server Side Rendering and Static Site Generation. Here the data is served statically but based on a certain condition or time the pages are rebuilt. This approach allows you to create updated static pages after you have built your site.

To use Incremental Site Regeneration add a revalidate prop to getStaticProps() method .

Example Code:

export async function getStaticProps(context) {
//make API calls here
  const { data } = await fetch(`Your url`);
  return {
    props: { data }, // will be passed to the page component as props
        revalidate:30 //The page will be built again in 30seconds
  };
}
Enter fullscreen mode Exit fullscreen mode

The static page is built on Build time and served to the user when the user requests. When the user again requests the page after 30 seconds, Next.js starts rebuilding the page again. So after rebuilding the updated page is shown to the user. The old page still remains in the cache. If a user requests the page again before the 30 seconds window, the same old page is shown.

Benefits:

  1. You are able to use SSG and SSR together.
  2. Great for SEO and Performance.

When to use:

  1. When you want speed of Static site but also wish to show updated data once in a while.
  2. When the data is updated but not often.

Use Case:

ISR can be used when you want to scale up a static site. In this case you don’t have to build the static site when a new update is made. You can pass in a revalidate prop and the page will rebuild itself. This will help you in scaling your Static sites.

Client Side data fetching

This is the approach what a plain React app uses. In this approach we fetch the data on the Client side of the application. Since the page is assembled on the client side we call this approach as Client Side Rendering. To handle CSR in next.js we use useEffect() hook. The useEffect() hook runs when the component loads. You can add your data fetching methods in useEffect() hook to perform data fetching on Client Side.

Example Code

const [users,setUsers] = useState(null)

    const fetchData=async()=>{
        try {
            const { data } = await axios.get(
              "https://jsonplaceholder.typicode.com/users"
            );
            setUsers(data)
            console.log(data)
        } catch (error) {
            console.log(error)
        }
    }

    useEffect(()=>{
        fetchData()
    },[])

Enter fullscreen mode Exit fullscreen mode

Benefits:

  1. The page gathers data at the client hence there is less load on the server.
  2. The page will always serve latest data.
  3. Great for user interactivity.

When to use:

  1. When your page has data which is updated very frequently(every minute).
  2. Where user interaction with the data is more.

Use Case:

Dashboard built with React/Next.js use this approach. You can create a Dashboard page and once the page is assembled you can make a request for the data using the useEffect() hook. You can add a threshold to set the page refresh. Hence when the threshold is passed the page refreshes and new data is fetched.

Conclusion

We have now learnt 4 ways of fetching data in Next.js. All the ways completely different from each other and have their own pros and cons. And you know the best thing about Next.js??

You don’t have to choose one for your project! You can select one way for one page and other for another page. You can choose the way you wish to fetch data on the need of that page. So in your next Hotel booking website you can have your home page generated Statically while you can generate your Listings page dynamically on Server!

Thanks for reading. I hope you learnt something new today. If you still have any problem feel free to message me on my twitter.

Top comments (0)