Next Js Fetch Data from API – Server and Client Side Method with Examples

In this tutorial, you will learn how to fetch data from a remote API using various methods. In the Nextjs application, we can fetch data on the server-side, or client-side or can also use a hybrid method to handle data on the server and the client side. We will also discuss their benefits and use cases with practical examples.

You will also learn detailed practical examples like how to use getServerSideProps to fetch data server-side and even if data is not loaded then how to use fetch data on the client to be on the safe side.

How to Fetch API Data in Nextjs application using Various Techniques?

 

Data Fetching in Next.js

Data fetching is an important part of web applications, especially data-driven sites. They retrieve data from a  remote server or a database via HTTP calls to the remote API services. The data reviewed is used to populate the components of the application.

In Next.js, there are various methods for fetching data which we are going to discuss in this comprehensive guide. We will walk you through each one’s examples, use cases and benefits.

 

Types of Data Fetching Techniques in Next.js

There are four primary methods of data fetching in Next.js which we have discussed below:

  • Server-Side Rendering (SSR)
  • Static Site Generation (SSG)
  • Incremental Static Regeneration (ISR)
  • Client-Side Rendering (CSR)

Let’s have a look at each type of technique in detail with examples and find out which one to deploy for your use case:

 

1) Server-Side Data Fetching

In Server-Side Rendering (SSR) method, data is fetched on each request in the Nextjs application. This means that every time a user visits a page, the data for that particular page is fetched from the server at that time. Thereafter the page is rendered with that data. This proves beneficial for dynamic and user-specific data which ensures the data is always up-to-date for each user every time.

The main benefits of using SSR are:

  • SEO: As the content is made available at the time of page load or before the page is rendered, it can be easily crawled and indexed by search engines.

Let’s have an example of server-side data fetching in Next.js:

// Import necessary modules
import { useState, useEffect } from 'react';

// This is your page component
const ServerSidePage = ({ serverData }) => {
  const [data, setData] = useState(serverData);

  // This useEffect will run when the component mounts
  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch('https://api.example.com/data');
      const newData = await res.json();
      setData(newData);
    };

    // If there's no data, fetch it
    if (!data) {
      fetchData();
    }
  }, []);

  // If there's no data, show a loading message
  if (!data) {
    return <div>Loading...</div>;
  }

  // Render the data
  return (
    <div>
      {data.map((item, index) => (
        <div key={index}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
};

// This function runs on the server and fetches the data
export async function getServerSideProps() {
  const res = await fetch('https://api.example.com/data');
  const serverData = await res.json();

  return {
    props: {
      serverData,
    },
  };
}

export default ServerSidePage;

ThegetServerSideProps is a special function provided by Next.js that runs on the server side before the page is rendered? This function fetches the data from the API and passes it as a prop to the ServerSidePage component.

The component then uses this data to render the page. If the data is not available for any reason for example, if the API is not working, the component will fetch the client sideline the -side for safer side using the fetchData function, that is inside the useEffect hook.

 

2) Static Generation and Incremental Static Regeneration

Static Generation (SSG) is another method of data fetching in Next.js. Unlike the SSR method we discussed in the previous section, the SSG method fetches data at build time and generates static HTML pages.

This means that the data for each page is fetched once when the site is built, and that same content for pages is shown to the users. This method is used for content that doesn’t need frequent updates or changes often like About Us, and Contact Us pages.

Incremental Static Regeneration (ISR) is like a hybrid method which allows updating the static content after it has been built, which prevents the need to rebuild the entire site. This is useful for content that is updated periodically or less frequently.

The benefits of SSG and ISR are:

  • Performance: Static files are served quickly, which leads to faster page load times and improved performance
  • SEO: Static pages can be crawled and indexed by search engines more easily.
  • Scalability: As data remains static, so such pages or sites can handle a lot of traffic as they only serve the same content to each user.

An example of using static generation and incremental static regeneration in Next.js:

import { useState, useEffect } from 'react';

// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get data
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  // By returning { props: data }, the component
  // will receive `data` as a prop at build time
  return {
    props: {
      data,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every second
    revalidate: 1, // In seconds
  };
}

// This function gets called at runtime
function Page({ data }) {
  // Render data...
  return (
    <div>
      {data.map((item) => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
}

export default Page;

ThegetStaticProps is a Next.js function that will run at the build time in a serverless function and fetches the data from a remote API. The fetched data is then passed as a prop to the Page component to render.

You will notice the revalidate option is set to 1, which means that if a new request comes in after 1 second from the last data generation of the page, Nextjs will attempt to re-generate the page with updated data. The re-generated page will then be served for requests after that.

 

3) Client-Side Data Fetching

The Client-Side Rendering (CSR) method of data fetching in Next.js is most common one, where data is fetched on the client-side and after the page has been loaded in the browser.

This means that the page is first rendered with no data, and then the data is fetched from a remote API and the page is updated with data received. This kind of client-side method is suitable for data which changes frequently, also index by search engines is not required.

The main Pros of using CSR are:

  • Interactivity: As data is fetched from API and rendered on the client side, it will allow for more interactivity between the user with the site.
  • Real-time updates: As data can be fetched and updated in real-time without requiring a page reload, so the updated data can be served to the users.

Let’s see how to use client-side data fetching in Next.js:

import { useState, useEffect } from 'react';

function Page() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch('https://api.example.com/data');
      const data = await res.json();
      setData(data);
    };

    fetchData();
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  // Render data...
  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
}

export default Page;

In this example, we used the useState and useEffect React hooks to fetch and render data on the client side. The fetchData function is called when the component mounts and the fetched data is stored in a state and rendered on the page.

 

4) Fetching Data with useEffect

The useEffect hook is a built-in React hook which allows performing side effects in the function components. Side effects could be data fetching, handling subscriptions, or manually changing the DOM elements.

The useEffect hook in Nextjs can be used to fetch data on the client side after the component has been rendered. This is how you can fetch data using useEffect in Next.js:

import { useState, useEffect } from 'react';

function Page() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch('https://api.example.com/data');
      const data = await res.json();
      setData(data);
    };

    fetchData();
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  // Render data...
  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
}

export default Page;

 

5) Fetching Data with SWR

SWR is a React Hooks library for remote data fetching created by the team behind Next.js. The name “SWR” is derived from stale-while-revalidate, which is an HTTP cache invalidation strategy. SWR technique allows us to fetch data in a fast, flexible and efficient way.

SWR has several benefits, like automatic caching, revalidation, focus tracking, and error retries. It is particularly useful for fetching data on the client side-side in the Nextjs applications.

import useSWR from 'swr';

async function fetcher(url) {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error('Error fetching data');
  }
  return res.json();
}

function Page() {
  const { data, error } = useSWR('https://api.example.com/data', fetcher);

  if (error) return <div>Error loading data</div>;
  if (!data) return <div>Loading...</div>;

  // Render data...
  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
}

export default Page;

The useSWR is used to fetch data from the API and the fetcher function is passed as the second argument to useSWR, which fetches the data and returns it.

If there is an error while fetching the data, it throws an error which is caught and handled by SWR.

 

Conclusion

We have coved various data fetching methods that can be easily used the d in the Next js application. We discussed how we can truly fetch data on the server-side, client-side or as a hybrid method. You have also learned how to use them practically with examples of each. I hope this will be beneficial to use in your application.

Leave a Comment

Your email address will not be published. Required fields are marked *