GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in Hapi

SQLi in Hapi.js isn't a framework failure—it's an implementation disaster. Whether you're using legacy 'pg' drivers or modern query builders, the moment you use string concatenation or unescaped template literals in your 'server.route' handlers, you've handed the keys to your DB to any script kiddie with a single quote. This guide kills the vulnerability at the source.

The Vulnerable Pattern

server.route({
  method: 'GET',
  path: '/api/users/{username}',
  handler: async (request, h) => {
    const { username } = request.params;
    // CRITICAL VULNERABILITY: Raw template literal allows OOB/Union-based SQLi
    const query = `SELECT * FROM users WHERE username = '${username}'`;
    const { rows } = await db.query(query);
    return rows;
  }
});

The Secure Implementation

The exploit vector in the vulnerable code is the direct injection of 'request.params' into the SQL string. A malicious actor could pass 'admin'--' to bypass logic. The secure implementation does two things: 1. It uses Hapi's built-in Joi validation to ensure the input matches expected patterns (defense-in-depth). 2. It utilizes the database driver's parameterization ($1). This sends the query template and the data in separate packets to the SQL engine, ensuring the input is treated strictly as a literal value, never as executable code.

server.route({
  method: 'GET',
  path: '/api/users/{username}',
  options: {
    validate: {
      params: Joi.object({ username: Joi.string().alphanum().max(30).required() })
    }
  },
  handler: async (request, h) => {
    const { username } = request.params;
    // FIX: Parameterized query (Prepared Statement)
    const query = 'SELECT * FROM users WHERE username = $1';
    const { rows } = await db.query(query, [username]);
    return rows;
  }
});
System Alert • ID: 6615
Target: Hapi API
Potential Vulnerability

Your Hapi API might be exposed to SQL Injection (Legacy & Modern)

74% of Hapi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.