How to get form data in next js 13 route handler – Reactjs

by
Ali Hasan
angular-forms next.js next.js13 reactjs

Quick Fix: In Next.js 13, to access form data in a route handler, you can use the FormData API. Here’s an example:

import { NextResponse } from 'next/server';

export async function POST(request) {
  const formData = await request.formData();
  const name = formData.get('name');
  const email = formData.get('email');
  return NextResponse.json({ name, email });
}

The Problem:

When using Next.js 13 route handler to handle form submissions, the formData() method returns an empty object, preventing the retrieval of form data. The form is posted to the /api route and is expected to be accessible through the request.formData() method in the route handler.

The Solutions:

Solution 1: Using request.formData()

In the route handler, you can use the `formData()` method on the `request` object to get the form data as follows:

import { NextResponse } from 'next/server';

export async function POST(request) {
  const formData = await request.formData();
  const name = formData.get('name');
  const email = formData.get('email');
  const myfile = formData.get('myfile');
  console.log(myfile);
  return NextResponse.json({ name, email });
}

This will allow you to access the form data in your route handler.

Solution 2: `async/await`

The `.formData()` method returns a Promise, which means it takes some time to resolve. To get the form data, you need to await the Promise:

export async function POST(request) {
  const data = await request.formData();
  return NextResponse.json({ data });
}

Solution 3: Using Form Data with Base64 Encoding

To resolve the issue of getting empty form data when using the formData() method in a Next.js 13 route handler, follow these steps:

  1. Convert the form file to base64:

    • Implement a getBase64() function that uses the FileReader API to convert the selected file to a base64 string.
  2. Create a new Form Data object:

    • Create a new instance of FormData and append the base64-encoded file to it.
  3. Update the route handler:

    • In the route handler, parse the request body and retrieve the "file" value.
    • Convert the "file" value back to a Buffer object.
    • Replace the original formData() with the newly created FormData object.

By performing these steps, you can successfully retrieve the form data, including the uploaded file, in your route handler.

Solution 4: Using ‘config’ and ‘formData’ methods

To access form data in a Next.js 13 route handler, follow these steps:

  1. Configure the runtime:

    • Add the following code to your api/route.js file to configure the runtime to ‘edge’:
      export const config = { runtime: 'edge' };
      
  2. Handle POST requests:

    • In your route handler, use the formData method to retrieve the form data:
      export default async function POST(request) {
        const formData = await request.formData();
      
  3. Access form data:

    • To access specific form fields, use the get() method on the formData object. For example, to get the value of the ‘name’ field:
      const name = formData.get('name');
      
  4. Return the response:

    • Return the form data as a JSON response using NextResponse.json(). For example:
      return NextResponse.json({ name });
      

Solution 5: Use `NextRequest` instead of `NextApiRequest`

Unlike earlier versions of NextJS, in v13, the `NextApiRequest` object is not available by default in the route handlers. Instead, use `NextRequest` as shown below:

“`ts
import { type NextRequest } from ‘next/server’;

export async function POST(request: NextRequest) {
  const data = await request.json();
  console.log({ data });
  // ...
}
```
</p>

Q&A

How to get form data in next js 13 route handler with edge runtime?

Use NextRequest instead of NextApiRequest. const data = await request.json();

How to get form data in next js 13 route handler when formData returns empty object?

formData returns Promise, await it const data = await request.formData();

How to get selected file in next js 13 route handler

Convert Base64 to Buffer, create a new form-data and send it.

Video Explanation:

The following video, titled "Using React Hook Form, Zod Validation and Server Actions in ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this video, we'll look at implementing forms in NextJs using the React-hook-form library, we'll then add validation using Zod, and at the ...