Multer upload errors come back as a 500 stack trace instead of a clean reply
MulterError with code LIMIT_FILE_SIZEShort answer
Multer delegates every upload error to Express. A file over the fileSize limit raises a MulterError with the code LIMIT_FILE_SIZE, a rejecting fileFilter raises whatever error you pass, and without an error handler the client gets the default 500 page. Add an error-handling middleware, and check that the limit is set in bytes.
Fix it fast
1Find out which cause you have
Catch the error where Multer raises it and print its class and code. A MulterError has a code; an error from your own fileFilter does not.
upload.single('photo')(req, res, (err) => { console.log(err && err.constructor.name, err && err.code); });2Match what you see, then jump to its fix
- 1
The error code is LIMIT_FILE_SIZE and the response is the default error pageThe upload exceeded the fileSize limit and nothing answers the clientFix - 2
Every upload fails with LIMIT_FILE_SIZE, even tiny filesfileSize is set in a unit other than bytesFix - 3
The error has no code, and the message is the text you passed to the callbackfileFilter rejects with an error that is not a MulterErrorFix - 4
Your handler exists, but the default page is still sent for Multer errorsThe error handler is not reached or has the wrong shapeFix
- 1
What does the error look like?
MulterError with code LIMIT_FILE_SIZELarge uploads end in a 500 response with a stack trace in developmentEvery file is refused after fileSize was set to a small numberA file rejected in fileFilter ends the request with an error, or is skipped without any message
Cause 1 of 4
The upload exceeded the fileSize limit and nothing answers the client
1Check
Multer says it delegates errors to Express, so a MulterError travels like any other error. With no error-handling middleware, Express's built-in handler answers, with the stack trace outside production.
grep -rn "limits" --include="*.js" --exclude-dir=node_modules .2Fix
Add an error-handling middleware after the routes. Separate MulterError from other errors, and answer a too-large file with 413, the status for a request larger than the server will process.
const multer = require('multer');
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
if (err instanceof multer.MulterError) {
const status = err.code === 'LIMIT_FILE_SIZE' ? 413 : 400;
return res.status(status).json({ error: err.code, field: err.field });
}
next(err);
});3Verify
Upload a file larger than the limit; the reply is your JSON with status 413.
curl -i -F "photo=@/path/to/big-file.bin" http://localhost:3000/uploadConfirmed by github.com
Cause 2 of 4
fileSize is set in a unit other than bytes
1Check
The fileSize limit is the maximum file size in bytes, and its default is Infinity. A value like 5 or 2000 therefore means five bytes or two kilobytes, not five megabytes.
grep -rn "fileSize" --include="*.js" --exclude-dir=node_modules .2Fix
Write the number as bytes, with the arithmetic visible.
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 5 * 1024 * 1024 }, // 5 MiB
});3Verify
A file below the limit now uploads, and one above it still triggers the handler.
curl -i -F "photo=@/path/to/small-file.png" http://localhost:3000/uploadConfirmed by github.com
Cause 3 of 4
fileFilter rejects with an error that is not a MulterError
1Check
In fileFilter, cb(new Error('...')) aborts the upload with that exact error, which is not a MulterError, so a handler that only looks for MulterError lets it fall through to the default 500. A cb(null, false) call skips the file silently instead.
grep -rn "fileFilter" -A8 --include="*.js" --exclude-dir=node_modules .2Fix
Give your own error a status, and read it in the error middleware. Use cb(null, false) only when skipping the file quietly is what you want.
const upload = multer({
dest: 'uploads/',
fileFilter(req, file, cb) {
if (file.mimetype !== 'image/png') {
const err = new Error('Only PNG files are allowed');
err.status = 400;
return cb(err);
}
cb(null, true);
},
});
app.use((err, req, res, next) => {
if (err.status === 400) {
return res.status(400).json({ error: err.message });
}
next(err);
});3Verify
Upload a non-PNG file; you get a 400 with your message.
curl -i -F "photo=@/path/to/notes.txt" http://localhost:3000/uploadConfirmed by github.com
Cause 4 of 4
The error handler is not reached or has the wrong shape
1Check
An error-handling function takes four arguments, (err, req, res, next), and must be defined after the routes it should cover. A handler registered before the upload route, or with three arguments, is skipped.
grep -n "app.use\|app.post\|(err, req, res, next)" server.js2Fix
Move the handler below the routes. If you prefer to handle the error inside one route, call the middleware yourself and inspect the error in its callback, as the Multer README shows.
app.post('/upload', (req, res) => {
upload.single('photo')(req, res, (err) => {
if (err instanceof multer.MulterError) {
return res.status(400).json({ error: err.code });
} else if (err) {
return res.status(500).json({ error: 'Upload failed' });
}
res.json({ file: req.file && req.file.filename });
});
});3Verify
A rejected upload now ends with your JSON instead of the default page.
curl -i -F "photo=@/path/to/big-file.bin" http://localhost:3000/uploadConfirmed by expressjs.com
How do I stop it coming back?
- Always set limits.fileSize (and files and fields) on a public upload route; the defaults are Infinity, and Multer's own documentation recommends limits as protection against denial of service.
- Write sizes as 5 * 1024 * 1024 so the unit is visible.
- Use one error middleware that tells MulterError apart from other errors and answers with 4xx, not 500.
- Treat the file name sent by the client as untrusted input.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Multer rejects the upload with Unexpected field
MulterError: Unexpected file field
Multer throws LIMIT_UNEXPECTED_FILE when a file arrives under a field name your route did not declare, or when more files arrive than the route allows.
4 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix