Error handler ignored when NODE_ENV=production Error handler ignored when NODE_ENV=production express express

Error handler ignored when NODE_ENV=production


If you are runing on production server, try to use some logging provider like "papertrailapp" to see the error occurs in your app.

enter image description here


I've just stumbled upon the same problem. It turned out it's caused by a transpiler optimization applied when building production bundle - this one: https://babeljs.io/docs/en/babel-plugin-minify-dead-code-elimination

Express' error handlers should have the signature (err, req, res, next) => { ... } (be of arity 4). In your example next is not used anywhere in errorMiddleware function body and thus it gets eliminated (optimized-out) from function signature in production code.

Solution:

  • use keepFnArgs: true plugin option - possibly through https://webpack.js.org/plugins/babel-minify-webpack-plugin/ webpack configuration:

    var MinifyPlugin = require("babel-minify-webpack-plugin")module.exports = {    // ...    optimization: {        minimizer: [            new MinifyPlugin({                deadcode: {                    keepFnArgs: true,                },            }, {}),        ],    }    // ...}
  • or alternatively pretend in your code that this argument is used:
    const errMiddleware = (err, req, res, _next) => {    // ... your code ...    // ...    // cheat here:    _next}