Node.js › Error Handling
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?
IntermediateAnswer
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'.