Fix Security Misconfiguration in Hapi
Hapi.js is often praised for its configuration-driven approach, but default settings are a goldmine for attackers. Misconfigurations typically manifest as verbose error leaks (stack traces), insecure cookie attributes, and missing security headers. To harden a Hapi instance, we must move beyond defaults by implementing strict state management and response interception to prevent information disclosure.
The Vulnerable Pattern
const Hapi = require('@hapi/hapi');const init = async () => { const server = Hapi.server({ port: 3000 });
server.route({ method: 'GET', path: '/data', handler: (request, h) => { // VULNERABILITY: Default settings leak stack traces to the client // and cookies lack Secure/HttpOnly flags by default. throw new Error('Database Connection Failed at 10.0.0.5:5432'); } }); await server.start();
}; init();
The Secure Implementation
The hardening process involves four critical layers: 1. **Security Headers**: Setting `routes.security: true` automatically injects industry-standard headers like X-Content-Type-Options and HSTS. 2. **Error Masking**: The `onPreResponse` extension point acts as a final firewall, catching 'Boom' error objects and stripping sensitive pathing or database strings before they reach the attacker. 3. **Cookie Hardening**: Explicitly defining `isSecure` and `isHttpOnly` prevents session hijacking via MitM or XSS. 4. **Debug Suppression**: Explicitly setting `debug: false` ensures the framework does not default to 'loud' logging in the HTTP response body.
const Hapi = require('@hapi/hapi');const init = async () => { const server = Hapi.server({ port: 3000, debug: false, // Disable debug output in responses routes: { security: true, // Enables HSTS, x-frame-options, no-sniff, etc. cors: { origin: [‘https://trusted.com’] } } });
// Secure Cookie Configuration server.state('session', { isSecure: true, isHttpOnly: true, sameSite: 'Strict', encoding: 'base64json', strictHeader: true }); // Global Error Sanitization server.ext('onPreResponse', (request, h) => { const response = request.response; if (response.isBoom && process.env.NODE_ENV === 'production') { const error = response.output.payload; error.message = 'Internal Server Error'; // Mask internal details return h.response(error).code(response.output.statusCode); } return h.continue; }); await server.start();
}; init();
Your Hapi API
might be exposed to Security Misconfiguration
74% of Hapi 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.