0
0
NextjsDebug / FixBeginner · 4 min read

How to Handle File Upload in Next.js: Simple Guide

In Next.js, handle file uploads by creating an API route that processes multipart form data using a library like formidable. On the client side, use a FormData object to send the file via fetch to the API route for processing and storage.
🔍

Why This Happens

Developers often try to upload files in Next.js by sending the file directly in JSON or without parsing multipart form data, which causes errors because Next.js API routes do not parse file uploads automatically.

javascript
export default function handler(req, res) {
  const file = req.body.file;
  res.status(200).json({ message: 'File received', file });
}
Output
Error or empty file data because req.body.file is undefined or empty
🔧

The Fix

Use the formidable library to parse incoming file uploads in the API route. On the client, send the file using FormData and fetch. This way, the server can read the file stream and save or process it.

javascript
import formidable from 'formidable';
import fs from 'fs';

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

export default async function handler(req, res) {
  const form = new formidable.IncomingForm();

  form.parse(req, (err, fields, files) => {
    if (err) {
      res.status(500).json({ error: 'Error parsing files' });
      return;
    }
    const file = files.file;
    const data = fs.readFileSync(file.filepath);
    // Example: save file or process it here
    res.status(200).json({ message: 'File uploaded successfully', filename: file.originalFilename });
  });
}
Output
{"message":"File uploaded successfully","filename":"example.png"}
🛡️

Prevention

Always disable Next.js default body parsing for file upload API routes by setting api.bodyParser = false. Use libraries like formidable or multer to handle multipart form data. On the client, use FormData to send files. Test uploads with small files first and handle errors gracefully.

⚠️

Related Errors

Common issues:

  • "Payload Too Large" error: Fix by increasing server limits or restricting file size.
  • "Cannot read property 'file' of undefined": Happens if body parsing is not disabled or form data is not sent correctly.
  • File permissions errors: Ensure server has write access if saving files.

Key Takeaways

Disable Next.js default body parser for file upload API routes with api.bodyParser = false.
Use formidable or similar libraries to parse multipart form data on the server.
Send files from the client using FormData and fetch for proper upload handling.
Test file uploads with small files and handle errors clearly.
Check server permissions and size limits to avoid common upload errors.