How To Send POST Request To External API In NextJS?
Last Updated :
25 Jul, 2024
Sending POST requests to external APIs in Next.js enables interaction with third-party services or your backend. This allows for data submission, form handling, and integration, enhancing your application's functionality.
Prerequisites:
Below are the approaches mentioned to send POST Request to External APIs in NextJS
Steps to Setup a NextJS App
Step 1: Create a NextJS application using the following command and answer a few questions.
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:
The updated dependencies in package.json file will look like:
"dependencies": {
"contentful": "^10.11.2",
"next": "14.2.3",
"react": "^18",
"react-dom": "^18"
}
Using Fetch Method
To send a POST request to an external API in Next.js we will use the traditional method. 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
// Filename: 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 | GeeksForGeeks</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/
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:
Example: The below example demonstrates the sending of POST requests to external API through our own API routes.
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('api/submit', {
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 | GeeksForGeeks</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>
</>
);
}
JavaScript
//File path: src/app/api/submit/route.js
import { NextResponse } from "next/server";
export async function POST(request) {
const { title, body, userId } = await request.json();
let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: "POST",
body: JSON.stringify({
title: title,
body: body,
userId: userId
}),
headers: {
'Content-type': 'application/json'
}
})
response = await response.json()
return NextResponse.json(response)
}
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/
Similar Reads
How to Send an HTTP POST Request in JS? We are going to send an API HTTP POST request in JavaScript using fetch API. The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request. Th
2 min read
How to Handle a Post Request in Next.js? 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 handle a post request in NextJS. A
2 min read
How to create and send POST requests in Postman? Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, and convert save the API to code for various languages(like JavaScript, and Python).
2 min read
How to set header request in Postman? Postman is a powerful API development tool that offers a feature known as environment variables. These variables are used for efficient testing and development of APIs by allowing users to manage dynamic values across requests easily. In this article, we will learn How you can set header requests in
2 min read
How to create a new request in Postman? Postman is a development tool that is used for testing web APIs i.e. Application Programming Interfaces. It allows you to test the functionality of any application's APIs. Almost every developer uses Postman for testing purposes. We can create any type of HTTP request in it such as GET, POST, PUT, D
2 min read