Error Handling, Logging and Monitoring
Two goals:
- Don't leak internals to users (stack traces, SQL errors, file paths, versions)
- Do log enough to detect and investigate attacks, without logging secrets
Packages
| Package | Use |
|---|---|
pino / winston | Structured (JSON) logging |
pino-http | Request logging for Express |
@sentry/node | Error tracking and alerting |
prom-client | Metrics for Prometheus/Grafana (spikes in 401/403/429) |
❌ Vulnerable
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message, stack: err.stack }); // leaks internals
});
logger.info('login', req.body); // logs the password✅ Secure
const pino = require('pino');
const logger = pino({
redact: ['req.headers.authorization', 'req.headers.cookie', '*.password', '*.token', '*.cardNumber'],
});
// Central error handler: last middleware
app.use((err, req, res, next) => {
const id = crypto.randomUUID();
logger.error({ err, id, path: req.path, userId: req.user?.id });
const status = err.status || 500;
res.status(status).json({
error: status < 500 ? err.message : 'Something went wrong',
id, // the user can report this; you look it up in the logs
});
});
// Don't crash silently
process.on('unhandledRejection', (e) => { logger.fatal(e); process.exit(1); });What to log (security events)
- Login success and failure, logout, password or MFA changes
- Access denied (403), validation failures, rate-limit hits
- Admin actions, permission changes, data exports
- Include: timestamp, user ID, IP, user agent, request ID, outcome
What NOT to log
Passwords, tokens, session IDs, API keys, full card numbers, OTPs, raw PII (mask it: a***@gmail.com).
Audit logs
For sensitive actions, keep an append-only audit trail (who, what, when, before/after) that app users, and ideally the app itself, cannot edit.
Checklist
- Generic 500 messages in production (
NODE_ENV=production) - Redact secrets in logs
- A request ID on every log line
- Alerts on spikes in failed logins, 403s and 5xx errors
- Logs shipped off the server (a hacker can wipe local logs)
- Keep logs for a defined time