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:
<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:
<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:
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:
import nextConnect from 'next-connect'
import multiparty from 'multiparty'
const middleware = nextConnect()
middleware.use(async (req, res, next) => {
const form = new multiparty.Form()
await form.parse(req, function (err, fields, files) {
req.body = fields
req.files = files
next()
})
})
export default middleware
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:
import middleware from 'middleware/middleware'
import nextConnect from 'next-connect'
const handler = nextConnect()
handler.use(middleware)
handler.post(async (req, res) => {
console.log(req.body)
console.log(req.files)
// ... handle file upload logic
})
export const config = {
api: {
bodyParser: false
}
}
export default handler
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!