What is the risk of exposing a raw error's stack trace in an API response, and how do you prevent it while still logging full details server-side?
Short answer
A stack trace can reveal internal file paths, library versions, database query structure, or other implementation details that could help an attacker understand and exploit the system further -- production error handlers should log the full error (including stack trace)…
Advertisement
AModel answer
A stack trace can reveal internal file paths, library versions, database query structure, or other implementation details that could help an attacker understand and exploit the system further -- production error handlers should log the full error (including stack trace) server-side for the engineering team, while returning only a sanitized, generic message to the actual API client, typically gated by an environment check to still show full details during local development for convenience.
app.use((err, req, res, next) => {
logger.error(err.stack); // full details, server-side only
const isDev = process.env.NODE_ENV !== 'production';
res.status(500).json({
error: 'Internal server error',
...(isDev && { stack: err.stack }), // only include stack trace outside production
});
});Real-world example
A penetration test flags that a company's production API was returning full stack traces (revealing the exact file structure and an outdated library version) in error responses; the fix gates stack-trace exposure to only occur when NODE_ENV isn't 'production'.
Likely follow-ups
- What other information beyond a raw stack trace should be scrubbed from error responses before they reach a client?
- How would you configure a logging tool to still capture this same detailed information without it ever reaching the actual HTTP response?
Related topics