How to Submit NextJS Form to API Using FormData ?

To submit a Next.js form to an API using FormData, you first need to create a form component within your Next.js application. Then, handle the form submission logic, ensuring it captures all necessary user input. Utilize the FormData API to package the form data, including any file uploads if applicable. Finally, employ fetch or a similar HTTP client library to dispatch a POST request to the designated API endpoint, transmitting the FormData payload seamlessly.

Approach To Submit NextJS Form To API Using FormData

  • We are going to use a FormData interface of JavaScript.
  • FormData interface represents the object, which contains the form data in the form of a key/value.
  • key is the name attribute of the input field and Value represents the value of the input field.
  • We have created a form and when a user submits the form, it sends the request to the API/submit endpoint where we have created our API endpoint.
  • In a route.js file, we have created a POST API route handler.
  • It will access the data using the get() method of FormData.

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:

Example: The below example demonstrate the form data submit to the API using FormData.

Note: Remove the included CSS file from the layout.js

JavaScript
//File path: src/app/api/submit/route.js

import { NextResponse } from "next/server";

//Handling POST request
export async function POST(req, res) {
    //Get the Form Data
    const Formdata = await req.formData();
    const name = Formdata.get('name');
    const age = Formdata.get('age');
    const city = Formdata.get('city');
    //Response 
    return NextResponse.json({ name, age, city })
}
JavaScript
//File path: src/app/page.js
'use client';
import React from 'react';

export default function Home() {
  const handleSubmit = async (event) => {
    event.preventDefault(); 

    const formData = new FormData(event.target); 

    try {
      let response = await fetch('/api/submit', {
        method: 'POST',
        body: formData,
      });
      response = await response.json()
      alert(`${response.name} ${response.age} ${response.city}`)
    } catch (error) {
      // Handle error
      console.error('Error submitting form:', error);
    }
  };

  return (
    <>
      <h1>Login Page</h1>
      <form onSubmit={handleSubmit}>
        <label>Name</label>
        <input type="text"
         placeholder="Enter Your Name"
         F name="name" required/>
        <br />
        <label>Age</label>
        <input type="text"
         placeholder="Enter Your Age"
          name="age" required/>
        <br />
        <label>City</label> 
        <input type="text" 
        placeholder="Enter Your City"
         name="city" required/>
        <br />
        <button type="submit">Submit</button>
      </form>
    </>
  );
}

Start your application using the command:

npm run dev

Output: