Open In App

How To Fetch Data From APIs In NextJS?

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Fetching data from APIs in Next.js can be done using built-in methods like getServerSideProps, getStaticProps, or client-side fetching with useEffect. This flexibility supports both server-side and static data fetching.

Prerequisites:

Approach

To fetch data From API in next.js we will simply use the JavaSript fetch method along with async and await. This method is used to get the data from the API as an asynchronous process and display it on the webpage when data is available.

For different purposes like server-side data fetching we can use it with built-in methods provided by Next.js for data fetching and use useEffect hook while working on client side.

Steps to Setup a NextJS App

Step 1: Create a NextJS application using the following command.

npx create-next-app@latest app_name

Step 2: It will ask you some questions, so choose as the following.

√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router?  ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

Step 3: After creating your project folder, move to it using the following command.

cd app_name

Project Structure:

fetch-api-client-structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "react": "^18",
    "react-dom": "^18",
    "next": "14.2.3"
  },
  "devDependencies": {
    "postcss": "^8",
    "tailwindcss": "^3.4.1"
  }

Example: Implementation to fetch data from APIs in NextJS.

// src/app/page.js

"use client";
import { useState } from "react";

export default function Home() {
	const [data, setData] = useState("");

	const fetchData = async () => {
		let response = await fetch("https://catfact.ninja/fact");
		response = await response.json();

		setData(response);
	};

	console.log(data);
	return (
		<>
			<button onClick={fetchData}>Fetch Data</button>
			<p>{data.fact}</p>
		</>
	);
}

Step to Run Application: Run the application using the following command from the root directory of the project

npm run dev

Output: Your project will be shown in the URL http://localhost:3000/

cde
How To Fetch Data From APIs In NextJS?



Next Article

Similar Reads

three90RightbarBannerImg