rapidapi.com
Open in
urlscan Pro
2606:4700:3108::ac42:2ae8
Public Scan
URL:
https://rapidapi.com/guides/how-to-use-fetch-api-in-next-js
Submission: On January 17 via api from BR — Scanned from DE
Submission: On January 17 via api from BR — Scanned from DE
Form analysis
1 forms found in the DOM<form class="form___StyledForm-sc-h8hb5g-2 dvpMcM"><input type="email" name="email" id="newsletterSubscriptionInput" placeholder="Enter your email" required="" class="form___StyledInput-sc-h8hb5g-3 gOPSGp"><button type="submit"
class="form___StyledButton-sc-h8hb5g-4 hXPMOi">Subscribe</button></form>
Text Content
API Guides More: API Developer Resourses Search for codelabs, guides and courses Sign up Back to all guides HOW TO USE FETCH API IN NEXT.JS? API • Tue Oct 11 2022 • 4 min read Saad Irfan Share Twitter Facebook LinkedIn JavaScript is extensively used in almost all the fields of Computer Sciences. One of its areas of use is the Web, where it utilizes browser APIs to support dynamic websites. JavaScript also offers a wide variety of frameworks and libraries to help the coding process easier, simpler, and more efficient. In this piece, we will look at how to use the fetch API in Next.js. So without any further ado, let’s jump in! NEXT.JS It is a web framework built on top of React.js. Next.js extends the capabilities of React.js by providing the developers with features like server-side rendering, static site generation, incremental static generation, a working REST API, file-system-based routing, dynamic routing, etc. It provides better optimization, additional structure, and features to your application. Since it extends React.js, you can start by writing all the React.js code and eventually add Next.js features to your application. You can render the application server-side, so all the data has been pre-fetched before loading the web app in the browser. Afterward, you can write a simple REST API without setting up a Node.js server. USE FETCH API Let’s do it in steps to make things simpler. → STEP #1 We need an API that we can call to learn how to use the fetch API in Next.js. For this, we will use RapidAPI Hub, which provides over 35,000+ APIs. We will use the Famous Quotes API from RapidAPI Hub, so please go ahead and subscribe to it. Subscribe to Famous Quotes API → STEP #2 Now we need to set up a Next.js application. The simplest way to do it is by running the following command in your terminal: sh Copy npx create-next-app next-app The command will create a Next.js project called next-app. If you want to change the name, you can just replace next-app with what you want. → STEP #3 Now open this directory in your preferred code editor. Afterward, run the application running the following command in your project terminal: sh Copy npm run dev It will start the development environment of your Next.js application. → STEP #4 Once you are done, open the index.js file inside the pages directory and delete all the code. Now copy and paste the following inside this file: js Copy import styles from '../styles/Home.module.css'; export default function Home() { const callAPI = async () => {}; return ( <div className={styles.container}> <main className={styles.main}> <button onClick={callAPI}>Make API call</button> </main> </div> ); } The above code will render a button that will execute callAPI function when clicked. We will use our fetch API inside the callAPI function to call APIs. Let’s learn how to do this. js Copy const callAPI = async () => { try { const res = await fetch( `https://famous-quotes4.p.rapidapi.com/random?category=all&count=2`, { method: 'GET', headers: { 'X-RapidAPI-Key': 'your-rapidapi-key', 'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com', }, } ); const data = await res.json(); console.log(data); } catch (err) { console.log(err); } }; The fetch API is asynchronous, so we need to await it. It is a function that takes the API endpoint as its first parameter. The second parameter of the fetch API is an object that contains data like HTTP method, request headers, request body, etc. We have made a GET request in the above code snippet. If you want to make a POST request, you can just replace GET with POST. Here is a sample code snippet of how you can make a POST request using fetch API in Next.js. js Copy const res = await fetch(`API-ENDPOINT`, { method: 'POST', body: {}, }); const data = await res.json(); console.log(data); You can see that the method is POST with a body key holding an object. This object will contain the request body that is sent along with a POST API request. Here is the final code that you can just copy and paste into your index.js file: js Copy import styles from '../styles/Home.module.css'; export default function Home() { const callAPI = async () => { try { const res = await fetch( `https://famous-quotes4.p.rapidapi.com/random?category=all&count=2`, { method: 'GET', headers: { 'X-RapidAPI-Key': 'your-rapidapi-key', 'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com', }, } ); const data = await res.json(); console.log(data); } catch (err) { console.log(err); } }; return ( <div className={styles.container}> <main className={styles.main}> <button onClick={callAPI}>Make API call</button> </main> </div> ); } We are calling the callAPI function on the onClick event handler of the button. It makes an API call using fetch API in a Next.js app. WRAP UP That’s all, folks! I hope you now understand how to use the fetch API inside the Next.js app to call other APIs. # fetch api next.js# fetch-api# use fetch api next.js Share Twitter Facebook LinkedIn MORE GUIDES Ushna Ijaz API DOCS FOR REST REST API DOCUMENTATION PROVIDES A CLEAR AND STRUCTURED EXPLANATION OF HOW TO USE THE API, INCLUDING ITS ENDPOINTS, PARAMETERS, AND RESPONSES. API Ushna Ijaz WHAT IS API FUZZING? API FUZZING IS A SOFTWARE TESTING TECHNIQUE THAT INVOLVES SENDING A LARGE VOLUME OF RANDOM INPUTS TO AN API TO UNCOVER VULNERABILITIES. API Ushna Ijaz API VS WEBHOOKS IN THIS GUIDE, WE WILL EXPLORE THE DIFFERENCES BETWEEN APIS AND WEBHOOKS, THEIR USE CASES, AND HOW TO CHOOSE THE RIGHT APPROACH FOR YOUR PROJECT. APIComparison Ushna Ijaz HOW TO USE AXIOS WITH OPENAI API? IN THIS GUIDE, WE'LL LEARN HOW TO USE AXIOS TO MAKE HTTP REQUESTS WITH THE OPENAI API FOR POWERFUL AI-POWERED NATURAL LANGUAGE PROCESSING. APIAxios Ushna Ijaz HOW TO USE AXIOS WITH DIFFERENT DATA FORMATS? LEARN HOW TO USE AXIOS TO MAKE HTTP REQUESTS WITH VARIOUS DATA FORMATS SUCH AS JSON AND XML. APIAxios Learn API Development tips & tricks.Subscribe to our newsletter with over 1.7 Million Developers Subscribe Follow us PRODUCT * Build APIs * Public API Hub * API Hub for Enterprise * Rapid API Client VSCode ENTERPRISE * Internal Hub * Partner Hub * Security * Customers * Vertical Solutions RESOURCES * EBooks & Guides * Whitepages & Reports * Data Sheets & One-Pagers * Videos * Webinars * Learn COMPANY * Careers * Pressroom/News * Events * Blog * Contact Us © Rapid 2023 TERMS OF SERVICEPRIVACY