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.

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.

JavaScript
//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>
    );
}
JavaScript
//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