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

Handling Slowloris Attacks

Implement strict timeout logic to prune connections that send partial, incomplete requests slowly.

In this lesson, you will learn how to defend your Node.js server against "Slowloris" attacks by implementing strict timeout policies that prune incomplete, sluggish requests.

What is a Slowloris Attack?

A Slowloris attack is a type of Denial of Service (DoS) where an attacker opens many connections to your server but sends HTTP headers extremely slowly. Because Node.js handles connections asynchronously, these "partial" requests can hang open, consuming your server's connection slots until there is no room left for legitimate users. To an attacker, it’s like clogging a door by standing in the frame and moving as slowly as humanly possible.

Implementing Strict Timeouts

The most effective way to counter this is to force your server to close any connection that doesn't "behave" within a specific timeframe. By default, Node.js servers keep connections open for a long time to allow for keep-alive functionality, but we can tighten these constraints.

We use the server.timeout property to set a maximum time (in milliseconds) of inactivity, and more importantly, we set server.headersTimeout to ensure the entire header block is received quickly.

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello World');
});

// If the client hasn't sent the full headers within 5 seconds, drop the connection
server.headersTimeout = 5000; 

// If the client goes silent for 10 seconds after the headers, drop the connection
server.timeout = 10000; 

server.listen(3000);

Why This Works

By setting headersTimeout, you effectively say: "If you start sending me a request, you must finish sending those headers within 5 seconds." If the attacker tries to send one header line every 10 seconds to keep the socket alive, the server will trigger the timeout and forcibly destroy the socket. This frees up your server's resources to handle actual traffic instead of waiting on malicious, incomplete data.

While you shouldn't set these values so low that they break mobile users on poor connections, 5 to 10 seconds is usually more than enough for a legitimate header exchange.

Key Takeaway: Protect your server from Slowloris attacks by configuring strict headersTimeout and timeout properties to prune sluggish, incomplete connections.