Description
Express’s development errorhandler middleware can send exception messages, stack traces, and internal object data to the requester. Registering it on a production or internet-facing server may expose those details.
Potential impact
Detailed errors can reveal internal paths or environment settings and help someone target the application. Production responses may also bypass the application’s intended error format or security policy.
Remediation
- In a private development environment, register
errorhandler()only whenprocess.env.NODE_ENV === "development". IfNODE_ENVis unset, Express returns"development"fromapp.get("env")by default. SetNODE_ENV=productionexplicitly in production. - Configure a separate production handler. Return a generic message with a
5xxstatus for server errors and preserve the appropriate4xxstatus for client errors. Record detailed exceptions only in restricted server logs, with secrets removed.
Examples
Before
javascript
const express = require("express");
const errorhandler = require("errorhandler");
const app = express();
app.use(errorhandler());
After
javascript
const express = require("express");
const errorhandler = require("errorhandler");
const app = express();
if (process.env.NODE_ENV === "development") {
app.use(errorhandler());
}
In the revised example, the middleware is registered only when NODE_ENV is explicitly development. The production error handler still needs to be configured.