Information disclosure through stack traces

Internal information exposed through stack traces in error responses

Description

An Express error response that includes err.stack can reveal the server’s internal call path to the client.

Potential impact

A trace may identify source files and line numbers, module versions or operating-system usernames in absolute paths.

Remediation

  • Pass errors to a central Express error handler with next(err). Return a suitable HTTP status and a short message. Keep stack details out of response bodies, JSON and headers, and turn off development error pages in production.
  • Include the same traceId in the response and the server log so support staff can find the event. If you also need stack traces, configure the logger to redact secrets before writing them. Restrict access to the logs and set a retention period.

Examples

Before

javascript
const express = require('express');
const app = express();

app.get('/item/:id', async (req, res) => {
  try {
    // Simulate an error during processing
    throw new Error('DB query failed');
  } catch (err) {
    // BAD: Expose the stack trace in the response body
    return res.status(500).send('Error occurred: ' + err.stack);
  }
});

module.exports = app;

After

javascript
const express = require('express');
const crypto = require('crypto');
const app = express();

// Example route
app.get('/item/:id', async (req, res, next) => {
  try {
    // Simulate an error during processing
    throw new Error('DB connection timeout');
  } catch (err) {
    return next(err); // Delegate to the central error handler
  }
});

app.use((err, req, res, next) => {
  const traceId = crypto.randomUUID();
  console.error('Request failed', { traceId });
  if (res.headersSent) return next(err);
  return res.status(500).json({ message: 'Internal Server Error', traceId });
});

module.exports = app;

Node.js rejects header values containing newlines. The first route exposes the trace in the response body. The revised handler logs only a fixed message and a traceId. Before the headers are sent, the handler returns HTTP 500 with a short message and the same traceId. If the headers have already been sent, it forwards the original error with next(err). Express’s default error handler can write that error to stderr even in production. Redact secrets when collecting stderr and restrict access to those logs.

References