How to Handle a Post Request in Next.js?
Approach to Handling a Post Request in NextJS
- We are going to use a POST request API route handler to handle the POST request in NextJS.
- NextJS provides different HTTP method API route handlers to handle the specific HTTP request.
- For example, We have created an Input field and a button.
- We have stored the data of the input field in a state.
- When a user clicks on the Send POST Request button, the sendPostRequest function will send a POST request with input field data.
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: After creating your project folder, move to it using the following command.
cd app_name
Project Structure:
Example: The below example demonstrate the handling of post request in NextJS.
//File path: src/app/page.js
'use client';
import { useState } from "react";
export default function Home() {
const [data, setData] = useState('')
const sendPostRequest = async () => {
let response = await fetch('http://localhost:3000/api/postfunction', {
method: "POST",
body: JSON.stringify(data)
})
response = await response.json();
alert(response.data)
}
return (
<div style={{ margin: "10px" }}>
<h1>Handling POST Request in Next.js</h1>
<input type="text"
placeholder="Enter Name"
style={{ padding: "10px 5px" }}
value={data}
onChange={(e) => setData(e.target.value)}
/>
<br /><br />
<button
onClick={sendPostRequest}
style={{ padding: "5px 10px" }}>
Send POST Request</button>
</div>
);
}
//File path: src/app/api/postfunction/route.js
import { NextResponse } from "next/server";
export async function POST(req, res) {
const data = await req.json()
return NextResponse.json({ "data": data })
}
Start your application using the command:
npm run dev
Output:
Contact Us