How to submit a form to an api in Next.js

Cover Image for How to submit a form to an api in Next.js
Ali Bentaleb
Ali Bentaleb

Forms are used to get data from user and submit it to a server or api to process this data later.

In this tutorial, we are going to build a form and submit it to an API using a react based app like Next.js

We are going to build a simple form using react which will ask the user for the first and last name and submit it to an api

Create the API

We need first to create an API, this will be a simple api deployed on next.js app

Under pages/api/, create myform.js and place this content :

export default function handler(req, res) {
  const body = req.body;

  res.status(200).json({ user: `${body.firstName} ${body.lastName}` });

This will serve as an API that returns an HTTP 200 OK and sends back the request body first name and last name

Create form and submit to the API

Now, let's create our form which will submit the data to the api we have created earlier:

import Head from "next/head";
import { useState } from "react";

export default function Test() {
  const [candidat, setCandidat] = useState({
    lastName: "",
    firstName: "",
  const [user,setUser]= useState()

  const onSubmit = async (e) => {
    if (candidat.lastName === "" || candidat.firstName === "")
      return alert("last name or first name is empty");

await fetch("/api/myform", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      body: JSON.stringify(candidat),
  return (
        <title> Next.js submit form</title>

        className="w-1/3 justify-center border-2 flex flex-col gap-4 m-4 p-2"
        <label htmlFor="Last name">Last name</label>
          className="border-2 border-gray-200  p-2"
          onChange={() => {
            setCandidat({ ...candidat, lastName: });

        <label htmlFor="First name">First name</label>
          className="border-2 border-gray-200  p-2"
          onChange={() => {
            setCandidat({ ...candidat, firstName: });

          className="bg-black text-white text-sm font-medium p-2 rounded "
      <div className="p-2">{user ? 'user is : '+ user:''}</div>

  • We create an object candidat using react useState hook based on what the user has typed
  • If the input is empty, we process this data on client side and alert them that data is empty
  • We use the html form with its method onSubmit which will take a method called onSubmit
  • onSubmit will prevent default so that when you click on submit, data will not be refreshed and so lost
  • We check first if user has typed in some data
  • Then we submit the data to our built api

To submit the form data to the api, the javascript object needs to be transformed to json using JSON.stringify so the data transferred can be read correctly by our api

fetch options are used to specify the headers and the http verb which is post in our case

tailwindcss classes are used to quicly style our react components, you can use plain css classes as well

Test configuration

Run your server and hit localhost:3000 or whatever port you are using for dev server

react form submit api

Now when you type in the fields and you hit submit you get the result returned by the API below the form like this:

react form submit api response


We have seen how to submit form data to an api using react and next.js

this data is transformed to json using json.stringify so that our api can process it and gives us back the response

To learn how to validate forms in client side, i recommend to check my article in this link

How to correctly set environme...How to set up Next.js with goo...