Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How to Send an HTTP POST Request in JS?
Next article icon

How to Handle a Post Request in Next.js?

Last Updated : 13 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

post-request-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:


Next Article
How to Send an HTTP POST Request in JS?
author
jaimin78
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Next.js

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 Send POST Request To External API In NextJS?
    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:NextJSJavaScriptReactJSBelow are the approaches mentioned to sen
    4 min read
  • How to use CORS in Next.js to Handle Cross-origin Requests ?
    NextJS simplifies server-side logic with its API routes, reducing the need for separate server maintenance. CORS, usually configured on the server, can be handled within NextJS API routes directly. These routes, integrated into the application codebase, allow control over request origins. By impleme
    7 min read
  • How to Catch All Routes in Next.js ?
    To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure. Catch all routesTo catch all routes in next js, We will Create a file named [...gfg].js
    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 access Raw Body of a Post Request in Express.js ?
    Raw Body of a POST request refers to unprocessed or uninterpreted data sent in the request before Express or any middleware processes or understands it. It's like raw ingredients before the cooking begins. In this article we will see various approaches to access raw body of a post request in Express
    3 min read
  • How do you handle nested routes in Express.js?
    In this article we are going to learn that how can we setup nested routes in Express JS. Nested routes are the routes that are defined within other routes. This is used to organize your code. We are going to implement the nested routes using the below given two approaches. Table of Content Using Exp
    2 min read
  • How to Redirect 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 Redirect in NextJS with different
    4 min read
  • How to Use Handle Get Request in Express.js ?
    Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the fundamental tasks in web development is handling HTTP requests, and GET requests are among the most common. This article will guide you through the process of handling GET requests in
    3 min read
  • How to Access Request Parameters in Postman?
    Request parameters are additional pieces of information sent along with a URL to a server. They provide specific details about the request, influencing the server's response. Parameters typically follow a 'Key=Value' format and are added to the URL in different ways depending on their type. Table of
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences