Course contentsShow
← Node.js
Lesson 570 of 1,9806. Networking and HTTP FundamentalsFree lesson

Header Size Constraints

Enforce strict limits on incoming header sizes to defend against buffer overflow and DoS attacks.

In this lesson, you will learn how to defend your server against memory exhaustion and Denial of Service (DoS) attacks by strictly limiting the size of incoming HTTP headers.

The Danger of Unbounded Headers

When a client sends an HTTP request, the headers (such as Cookie, User-Agent, or Authorization) are parsed into memory. By default, Node.js imposes a limit (usually 16KB) to prevent malicious actors from sending gargantuan, malformed headers designed to fill up your server's RAM. If an attacker sends a header that is several megabytes long, your server might crash as it attempts to buffer that data, leading to a classic DoS scenario.

Implementing Strict Constraints

While Node.js handles basic protection, you should explicitly configure these constraints to match your application's actual needs. You can control this when creating your server using the maxHeaderSize option.

If you know your largest legitimate header (e.g., a complex JWT authentication token) is only 8KB, you should set your limit to something close to that rather than relying on the default.

const http = require('http');

const server = http.createServer({
  // Limit headers to 8KB (8192 bytes) to prevent memory attacks
  maxHeaderSize: 8192 
}, (req, res) => {
  res.end('Request accepted.');
});

server.listen(3000);

Why This Matters

Think of maxHeaderSize as a "bouncers at the door" mechanism. By rejecting oversized requests early in the HTTP parsing phase, you save your application from the overhead of processing, parsing, or logging data that could be part of a buffer overflow attempt. It acts as a primary filter that protects your memory management layer, ensuring that no single connection can monopolize your server's resources. Even if you have implemented robust error handling or rate limiting, a single massive header can still bypass those systems if the parser crashes while trying to read the incoming stream.

Key Takeaway: Restricting maxHeaderSize is a critical defense-in-depth strategy that prevents malicious clients from triggering memory exhaustion by forcing your server to buffer excessively large HTTP headers.