Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Multer upload errors come back as a 500 stack trace instead of a clean reply

ErrorMulterError with code LIMIT_FILE_SIZE

Short 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.

  • Applies to Multer (current npm release), Express 5, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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);
    });
  2. 2Match what you see, then jump to its fix

    1. 1The 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. 2Every upload fails with LIMIT_FILE_SIZE, even tiny filesfileSize is set in a unit other than bytesFix
    3. 3The 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. 4Your handler exists, but the default page is still sent for Multer errorsThe error handler is not reached or has the wrong shapeFix

What does the error look like?

  • MulterError with code LIMIT_FILE_SIZE
  • Large uploads end in a 500 response with a stack trace in development
  • Every file is refused after fileSize was set to a small number
  • A 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/upload

Confirmed by github.com

Did this fix it?

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/upload

Confirmed by github.com

Did this fix it?

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/upload

Confirmed by github.com

Did this fix it?

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.js

2Fix

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/upload

Confirmed by expressjs.com

Did this fix it?

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.