Next.js: Error 413 Request Entity Too Large on file upload

Viewed 952

I'm having troubles trying to upload large files with Next.js. I've created an onChange function on my input file, here's the code:

const handleFileUpload = () => new Promise(async (resolve) => {
    if(ref.current?.files){
        const formData = new FormData()
        Object.entries(ref.current.files).map(([i, f]) => {
            return formData.append(`${id}_${i}`, f)
        })

        const config = {
            headers: { 'content-type': 'multipart/form-data' },
            onUploadProgress: (event) => {
                const p = Math.round((event.loaded * 100) / event.total);
                setProgress(p)
            }
        }

        try{
            const response = await axios.post('/api/upload-file', formData, config);
            resolve(response)
        }
        catch(err){
            console.log(err)
        }
   }
}

And this is my /api/upload-file.js

import nextConnect from 'next-connect';
import multer from 'multer';
import { METHOD_NOT_ALLOWED, NOT_IMPLEMENTED, OK } from '../../utils/statusCode';

const upload = multer({

    storage: multer.diskStorage({
        destination: './public/upload',
        filename: (req, file, cb) => cb(null, file.originalname),
    })

})

const apiRoute = nextConnect({

    onError(error, req, res){
        res.status(NOT_IMPLEMENTED).json({error: `Errore: impossibile procedere. ${error.message}`})
    },
    onNoMatch(req, res){
        res.status(METHOD_NOT_ALLOWED).json({error: `Metodo ${req.method} non permesso`})
    }

})

apiRoute.use(upload.any())
apiRoute.post((req, res) => res.status(OK).json({data: 'success'}))

export default apiRoute

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

It works perfectly with small files, but I receive a 413 error with larger ones (even 1 or 2MB), is there something I'm missing here?

I'm using Next.js 12.0.3

1 Answers
Related