How to Upload Files in a Next.js Form
In this article, I will guide you through the process of uploading files in a Next.js form. By default, Next.js does not allow file uploads in forms, but with a few adjustments, we can make it work.
First, let’s take a look at the form structure in a Next.js page:
1 | <form method="post" action="/api/new" enctype="multipart/form-data">...</form> |
Here, we have a standard HTML form that calls an API endpoint. Inside this form, there is a file input control:
1 | <input name="logo" type="file" /> |
Unfortunately, we cannot retrieve the file data in the API route directly. In order to handle file uploads in Next.js, we need to install two packages: next-connect
and multiparty
. You can install them using the following command:
1 | npm install next-connect multiparty |
Next, create a middleware
folder in the root of your Next.js project. Inside this folder, create a file named middleware.js
with the following content:
1 | import nextConnect from 'next-connect' |
This middleware file will handle parsing the incoming request and extracting the file data.
Now, let’s modify the API route. Instead of the usual structure, we will use the nextConnect
middleware and the multiparty
middleware we created:
1 | import middleware from 'middleware/middleware' |
By using nextConnect
and applying the middleware
we created, we can now access the file data in the API route. You can handle the file upload logic as per your requirements.
Remember to configure the bodyParser
option to false
in the config
object. This is necessary because we are using a custom middleware to handle file uploads.
Once you have made these changes, restart your Next.js server and you should be able to retrieve the file data in the API route.
That’s it! You have successfully enabled file uploads in a Next.js form. Happy coding!
tags: [“Next.js”, “file upload”, “form handling”, “API”]