GuardAPI Logo
GuardAPI

Fix API Rate Limit Exhaustion in Hapi

Rate limit exhaustion in Hapi allows attackers to flood endpoints, causing Denial of Service (DoS) or brute-forcing sensitive logic. Without a governor, your Hapi server is a sitting duck for resource depletion. We mitigate this by integrating hapi-rate-limit to enforce request quotas per IP address.

The Vulnerable Pattern

const Hapi = require('@hapi/hapi');

const init = async () => { const server = Hapi.server({ port: 3000 });

// VULNERABLE: No rate limiting logic. // An attacker can spam this endpoint to exhaust memory or CPU. server.route({ method: ‘POST’, path: ‘/api/login’, handler: (request, h) => { return { status: ‘processing’ }; } });

await server.start(); }; init();

The Secure Implementation

The fix involves registering the 'hapi-rate-limit' plugin to intercept incoming requests before they hit the route handler. The 'userLimit' and 'userCache' settings define the threshold and the window for blocking. By tracking 'ip', we ensure that a single source cannot overwhelm the server. In a distributed environment, use a Redis-backed cache for the 'userCache' option to maintain a global state across multiple Hapi nodes.

const Hapi = require('@hapi/hapi');
const RateLimit = require('hapi-rate-limit');

const init = async () => { const server = Hapi.server({ port: 3000 });

// SECURE: Register rate-limiting plugin await server.register({ plugin: RateLimit, options: { enabled: true, userLimit: 5, // Max 5 requests userCache: { expiresIn: 60000 // Per minute }, userAttribute: ‘ip’, // Track by IP pathLimit: false, headers: true // Send X-RateLimit headers } });

server.route({ method: ‘POST’, path: ‘/api/login’, handler: (request, h) => { return { status: ‘secure_processing’ }; } });

await server.start(); }; init();

System Alert • ID: 5594
Target: Hapi API
Potential Vulnerability

Your Hapi API might be exposed to API Rate Limit Exhaustion

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.