Fix Improper Error Handling in Fastify
Improper error handling in Fastify is a prime source for Information Disclosure (CWE-209). Defaulting to raw error serialization leaks stack traces, environment variables, and internal file paths to unauthenticated attackers. As an AppSec researcher, your goal is to ensure the framework never returns internal state, only sanitized, predictable JSON responses.
The Vulnerable Pattern
const fastify = require('fastify')();
fastify.get(‘/api/data’, async (request, reply) => { try { const data = await database.query(‘SELECT * FROM users WHERE id = ’ + request.query.id); return data; } catch (err) { // VULNERABILITY: Directly returning the error object leaks the stack trace // and database driver internals to the client. return reply.status(500).send(err); } });
The Secure Implementation
The vulnerable code fails because it allows the catch block to serialize the raw 'err' object into the HTTP response. In a production environment, this exposes the logic of the application and the underlying infrastructure. The secure implementation uses 'setErrorHandler' to decouple internal logging from client-facing responses. By logging the full error to a secure sink (via request.log) and returning a generic JSON object with a correlation ID (request.id), we maintain observability without compromising the security posture of the application.
const fastify = require('fastify')({ logger: true });// Global error handler to sanitize all outgoing error payloads fastify.setErrorHandler(function (error, request, reply) { // Log the full error internally for debugging (Pino) request.log.error(error);
// Handle validation errors specifically if (error.validation) { return reply.status(400).send({ status: ‘error’, message: ‘Invalid input parameters’ }); }
// Mask internal server errors from the client reply.status(500).send({ status: ‘error’, message: ‘An internal server error occurred’, reference: request.id // Provide a correlation ID for logs instead of a stack trace }); });
Your Fastify API
might be exposed to Improper Error Handling
74% of Fastify 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.