Fix Improper Error Handling in Polka
Polka's minimalism is its strength, but its default error handling is a liability. Out of the box, failing to provide a custom 'onError' handler can lead to stack trace leakage and internal path disclosure. In a production environment, this gives attackers a blueprint of your server-side logic, dependency versions, and file structure. Real AppSec means intercepting every exception and returning sanitized, generic responses while logging the forensic details internally.
The Vulnerable Pattern
const polka = require('polka');
polka() .get(‘/api/data’, (req, res) => { // Simulate a failure that leaks internal logic const data = db.querySync(‘SELECT * FROM users’); res.end(data); }) .listen(3000, err => { if (err) throw err; console.log(’> Running on localhost:3000’); });
The Secure Implementation
The vulnerable code relies on Polka's default behavior, which doesn't guarantee data sanitization when an unhandled exception occurs. The secure version implements a centralized 'onError' middleware. This handler differentiates between environments; it logs the full stack trace to an internal sink (like stdout or a file) for debugging but returns a generic 'Internal Server Error' message to the client. Additionally, wrapping route logic in try/catch blocks and passing errors to 'next(err)' ensures that even asynchronous failures are caught by the security boundary.
const polka = require('polka');// Custom error handler to prevent info disclosure function onError(err, req, res, next) { const isDev = process.env.NODE_ENV === ‘development’; console.error(
[ERROR] ${err.stack}); // Internal loggingres.statusCode = err.code || err.status || 500; res.setHeader(‘Content-Type’, ‘application/json’);
// Never expose stack traces in production res.end(JSON.stringify({ error: isDev ? err.message : ‘Internal Server Error’, id: req.headers[‘x-request-id’] || ‘N/A’ })); }
const app = polka({ onError });
app.get(‘/api/data’, async (req, res, next) => { try { const data = await db.query(‘SELECT * FROM users’); res.end(JSON.stringify(data)); } catch (err) { // Explicitly pass error to the central handler next(err); } });
app.listen(3000);
Your Polka API
might be exposed to Improper Error Handling
74% of Polka 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.