Fetching Data from External API and Pass it to a Component in Next.js
Fetching Data from an External API in Next.js
Fetching data from an external API is a common requirement in modern web applications. In this guide, you’ll learn how to use Next.js to call an external API on the server, then pass the data into a React component for rendering.
Step 1: Create a Next.js Project
First, create a new Next.js project. Run this command in your terminal:
npx create-next-app my-app
This creates a new Next.js project called my-app in a folder with the same name.
Step 2: Install Axios
Next, install the axios library, a popular HTTP client for making API requests:
npm install axios
Step 3: Create the Card Component
Now create a new component in your Next.js project. In this example, we’ll call it Card. This component will be responsible for displaying the data fetched from the API:
import React from 'react'
export default function Card({ data }) {
return (
<div>
<h1>Data List</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
)
}
The Card component receives the data prop and renders an unordered list. Each list
item is identified by its id and displays the corresponding name.
Step 4: Fetch Data with getServerSideProps
Now we need a way to fetch data from the API and pass it to the Card component. Next.js provides a built-in function called getServerSideProps that runs on the server for each request and passes data to your page as props:
import axios from 'axios'
const API_URL = 'https://your-api-url.com/data'
export async function getServerSideProps() {
const res = await axios.get(API_URL)
const data = await res.data
return {
props: {
data,
},
}
}
-
This example uses the
axioslibrary to call theAPI_URL, then passes the response data as props to your page component. Replace'https://your-api-url.com/data'with your real API endpoint. -
Always add error handling (for example, using a
try/catchblock or the.catch()method on the axios promise) to handle failed requests gracefully. - With getServerSideProps, you can fetch external data on the server and ensure your components always render with the latest data available at request time.