How to use Fetch Method In Next.js

In this approach, we will use the traditional fetch method to send a POST request to an external API. We have used a state to store the value of the input field, and when the submit button is clicked, it sends a POST request to the external API.

Example: The below example demonstrates the sending of post requests to external API using the fetch method.

JavaScript
//File path: src/app/page.js

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

export default function Home() {
  const [title, setTitle] = useState('')
  const [body, setBody] = useState('')

  const submitData = async () => {
      let response = await fetch('https://jsonplaceholder.typicode.com/posts',{
        method:"POST",
        body:JSON.stringify({
          title:title,
          body:body,
          userId:1
        }),
        headers:{
          'Content-type': 'application/json'
        }
      }) 
      
      response = await response.json()

      alert(JSON.stringify(response))
  }

  return (
    <>
        <h2>External Post API Request | w3wiki</h2>
        <input type="text" 
        value={title}
        onChange={(e)=>setTitle(e.target.value)}
        placeholder="Enter Post Title"/>

        <input type="text" 
        value={body}
        onChange={(e)=>setBody(e.target.value)}
        placeholder="Enter Post Body"/>
        <button onClick={submitData}>Submit</button>
    </>
  );
}

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/

How To Send POST Request To External API In NextJS?

NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about how to send post requests to external API in NextJS.

Prerequisites:

Below are the approaches mentioned to send POST Request to External APIs in NextJS

Table of Content

  • Using Fetch Method
  • Using Next.js API Route

Similar Reads

Steps to Setup a NextJS App

Step 1: Create a NextJS application using the following command and answer a few questions....

Using Fetch Method

In this approach, we will use the traditional fetch method to send a POST request to an external API. We have used a state to store the value of the input field, and when the submit button is clicked, it sends a POST request to the external API....

Using Next.js API Route

In this approach, we have developed a separate POST API using Next.js API Routes. We call the External API by utilizing our Next.js API. We use a state to store the value of the input field. When the submit button is clicked, a post request is sent to our own created API, which in turn sends a post request to the external API....

Project Structure:

...

Contact Us