Display API Response on Page in Next.js

Display API Response on Page in Next.js
Photo by Skyler Smith / Unsplash

In a Next.js application, you can use the getServerSideProps or getStaticProps method to fetch data from an API and pass it to a page as props.

getServerSideProps is used to fetch data at runtime on the server, while getStaticProps fetches data at build time, and is intended for scenarios where data is not expected to change frequently.

Here's an example of how you might use getServerSideProps to fetch data from an API and display it on a page:

import axios from 'axios';

export default function Home({ data }) {
  return <div>{JSON.stringify(data)}</div>;
}

export async function getServerSideProps() {
  const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
  const data = response.data;

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

In this example, the getServerSideProps method uses the axios library to make a GET request to the JSONPlaceholder API and fetch a list of posts. The response data is then passed to the component as a data prop.

Inside the component, you can use this data to display the results on the page. In this example, I just used JSON.stringify(data) to display the raw json data, but you can use the data to create dynamic UI.

You can also use getStaticProps in a similar fashion by replacing getServerSideProps with getStaticProps and instead of making API call in the function you could fetch data from a JSON file or other data store.

Keep in mind that the data received by getStaticProps will only be built once during build time, so it's only suitable if data is not going to change frequently and you can anticipate the changes at build time.