Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How to fetch data from APIs using Asynchronous await in ReactJS ?
Next article icon

How To Fetch Data From APIs In NextJS?

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • NPM & NodeJS
  • ReactJS
  • React Hooks
  • React Router

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.

JavaScript
// 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
How to fetch data from APIs using Asynchronous await in ReactJS ?
author
jaimin78
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Next.js
  • Next.js - Questions

Similar Reads

  • How to Fetch Data From an API in ReactJS?
    ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, we’ll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
    5 min read
  • How to Load Data from a File in Next.js?
    Loading Data from files consists of using client-side techniques to read and process files in a Next.js application. In this article, we will explore a practical demonstration of Load Data from a File in Next.js. We will load a validated CSV input file and display its contents in tabular format. App
    3 min read
  • How to fetch data from APIs using Asynchronous await in ReactJS ?
    Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. PrerequisitesReact JSFetch data from APIApproachTo
    3 min read
  • How to Get Data from API in Python Flask
    In modern web development, APIs (Application Programming Interfaces) play a crucial role in enabling the interaction between different software systems. Flask, a lightweight WSGI web application framework in Python, provides a simple and flexible way to create APIs. In this article, we'll explore ho
    2 min read
  • How to Fetch data faster in Next.js?
    NextJS, a popular React framework provides various approaches to fetch data efficiently. Optimizing data fetching can significantly improve the performance and user experience of your NextJS applications. We will discuss different approaches to Fetch data faster in NextJS: Table of Content Static Ge
    6 min read
  • How to Add ChartJS in NextJS 13?
    Chart.js in Next.js is the package used to create interactive and visually appealing charts, such as line charts, bar charts, and more, seamlessly integrated into Next.js applications. In this article, we will explore the demonstration of various charts in the NextJS application. Table of Content Im
    3 min read
  • How to Create a Next.js form ?
    Forms are an essential part of many web applications, allowing users to input data and interact with the website. Next.js, with its powerful features for building server-rendered React applications, provides an ideal platform for creating forms. In this article, we'll explore step-by-step how to cre
    4 min read
  • How To Use JavaScript Fetch API To Get Data?
    An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
    4 min read
  • How to use JavaScript Fetch API to Get Data ?
    The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests.  Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
    2 min read
  • How to handle data fetching in React-Redux Applications ?
    Data fetching in React-Redux applications is a common requirement to retrieve data from APIs or other sources and use it within your components. This article explores various approaches to handling data fetching in React-Redux applications, providing examples and explanations for each approach. Tabl
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences