GuardAPI Logo
GuardAPI

Fix Lack of Resources & Rate Limiting in Hapi

Hapi is robust, but it doesn't protect your resources by default. Without rate limiting and payload constraints, your application is a sitting duck for Denial of Service (DoS) attacks. An attacker can flood expensive endpoints or send massive payloads to exhaust memory and CPU, effectively nuking your event loop. You need to implement strict quotas at the plugin level to ensure availability.

The Vulnerable Pattern

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

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

server.route({ method: ‘POST’, path: ‘/api/resource-intensive’, handler: (request, h) => { // VULNERABILITY: No rate limiting and no payload size limits. // An attacker can spam this route or send a 500MB JSON body. return { status: ‘Processing…’ }; } });

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

The Secure Implementation

The fix involves a two-pronged defense. First, we set 'payload.maxBytes' in the server configuration to kill large incoming requests before they are fully buffered into memory, preventing memory-based DoS. Second, we integrate the 'hapi-rate-limit' plugin. This tracks requests by IP address (userAttribute) and enforces a sliding window quota. By applying a specific 'userLimit' of 5 to the sensitive route, we ensure that even if an attacker bypasses global limits, they cannot hammer the most resource-heavy parts of the logic. Requests exceeding the quota are automatically rejected with a 429 Too Many Requests status.

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

const init = async () => { const server = Hapi.server({ port: 3000, payload: { maxBytes: 1048576 // 1) Limit global payload to 1MB to prevent memory exhaustion } });

// 2) Register rate limiting plugin await server.register({ plugin: RateLimit, options: { enabled: true, userLimit: 100, // Max 100 requests per window userAttribute: ‘ip’, pathLimit: 50 } });

server.route({ method: ‘POST’, path: ‘/api/resource-intensive’, config: { plugins: { ‘hapi-rate-limit’: { userLimit: 5, // 3) Stricter limit for expensive routes windowLimit: 60000 // 1 minute window } } }, handler: (request, h) => { return { status: ‘Securely processing…’ }; } });

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

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

Your Hapi API might be exposed to Lack of Resources & Rate Limiting

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.