DEV Community

Mazin Ashfaq
Mazin Ashfaq

Posted on

Handling `multipart/form-data` in Next.js

When working with Next.js, handling file uploads can become a bit tricky, especially when dealing with multipart/form-data. In this guide, I'll explain how I integrated Fastify, Multer, and Axios to effectively handle these file uploads and interact with an external API.

1. Why the need for Fastify and Multer?

Next.js's default body parser doesn't handle multipart/form-data out of the box. Fastify is a web framework that can be easily integrated with Next.js for enhanced request processing. On the other hand, Multer is a middleware for Express.js (and Fastify with the right plugins) that makes it easy to handle multipart/form-data.

2. Setting up Fastify with Multer:

Firstly, you'll need to install necessary packages:

npm install multer fastify-multipart
Enter fullscreen mode Exit fullscreen mode

To use them with Fastify:

import fastifyMultipart from 'fastify-multipart';

const server = fastify();
server.register(fastifyMultipart);
Enter fullscreen mode Exit fullscreen mode

3. Configuring the Next.js API Route:

Now, let's set up the Next.js API route:

import multer from 'multer';

const storageConfig = multer.memoryStorage();
const upload = multer({ storage: storageConfig });

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(req, res) {
  upload.single('file')(req, null, async (err) => {
    if (err) {
      return res.status(500).json({ error: 'Upload error.' });
    }

    const file = req.file;
    const formData = new FormData();
    formData.append('file', file.buffer, { filename: file.originalname, contentType: file.mimetype });

    try {
      const response = await axios.post('YOUR_EXTERNAL_API_ENDPOINT', formData, {
        headers: formData.getHeaders(),
      });
      res.status(200).json(response.data);
    } catch (error) {
      res.status(500).json({ error: 'External API error.', details: error.message });
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

This method provides a streamlined way to handle file uploads in Next.js, allowing you to focus more on other aspects of your application. Integrating Fastify and Multer takes care of the heavy lifting, making it simpler to manage multipart/form-data and interact with external services.

Remember to replace 'YOUR_EXTERNAL_API_ENDPOINT' with the actual endpoint of the external API you're working with. Happy coding!


Top comments (0)