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:
-
Convert the form file to base64:
- Implement a
getBase64()
function that uses theFileReader
API to convert the selected file to a base64 string.
- Implement a
-
Create a new Form Data object:
- Create a new instance of
FormData
and append the base64-encoded file to it.
- Create a new instance of
-
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 createdFormData
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:
-
Configure the runtime:
- Add the following code to your
api/route.js
file to configure the runtime to ‘edge’:export const config = { runtime: 'edge' };
- Add the following code to your
-
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();
- In your route handler, use the
-
Access form data:
- To access specific form fields, use the
get()
method on theformData
object. For example, to get the value of the ‘name’ field:const name = formData.get('name');
- To access specific form fields, use the
-
Return the response:
- Return the form data as a JSON response using
NextResponse.json()
. For example:return NextResponse.json({ name });
- Return the form data as a JSON response using
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.
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 ...
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.
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 ...