Fix Improper Error Handling in Express
Improper error handling in Express is a primary vector for Information Disclosure. Default error responses or lazy 'res.send(err)' calls leak stack traces, module paths, and database schemas, providing attackers with a roadmap of your internal architecture. To secure an Express app, you must decouple internal debugging information from client-side responses.
The Vulnerable Pattern
app.get('/api/data', async (req, res) => {
try {
const data = await database.query(req.query.id);
res.json(data);
} catch (err) {
// VULNERABILITY: Sending the raw error object to the client
// This leaks stack traces, DB connection strings, and logic flaws.
res.status(500).json(err);
}
});
The Secure Implementation
The fix involves two critical steps: Centralization and Sanitization. First, stop handling errors inside individual routes; use 'next(err)' to forward them to a global error-handling middleware (defined with four arguments: err, req, res, next). Second, implement environment-aware logic. In production, never return the 'err' object or stack traces. Return a generic 'Internal Server Error' and a unique correlation ID if possible. Log the actual error to a secure, server-side sink like Winston or Sentry for developer review.
// 1. Define a centralized error-handling middleware app.use((err, req, res, next) => { const isProduction = process.env.NODE_ENV === 'production';// Log the full error internally for debugging console.error(err.stack);
// Send a sanitized response to the client res.status(err.status || 500).json({ error: { message: isProduction ? ‘Internal Server Error’ : err.message, …(isProduction ? {} : { stack: err.stack }) } }); });
// 2. Use ‘next(err)’ in controllers app.get(‘/api/data’, async (req, res, next) => { try { const data = await database.query(req.query.id); if (!data) return res.status(404).json({ error: ‘Not Found’ }); res.json(data); } catch (err) { // Pass the error to the global handler next(err); } });
Your Express API
might be exposed to Improper Error Handling
74% of Express apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.