andrzej1_1
andrzej1_1

Reputation: 1193

Disabling HTTP Keep-Alive in Node.js

I want to completely disable Keep-Alive in Node.js server, but setKeepAlive(false) does not have any effect. This is sample code:

var http = require('http')

var server = http.createServer(function(req, res) {
    res.end('Hello Node.js Server!')
})

server.on('connection', function(socket) {
    socket.setKeepAlive(false)
})

server.listen(8080)

As you can see, after opening http://127.0.0.1:8080, keep-alive header is present: browser-request

Am I doing something wrong?

Info: I am running node v10.1.0, but it also does not work on v8.11.2.

Upvotes: 4

Views: 4700

Answers (1)

Shuhei Kagawa
Shuhei Kagawa

Reputation: 4777

You can disable HTTP Keep-Alive by setting Connection: close header. This is necessary because Keep-Alive is enabled by default in HTTP 1.1.

var server = http.createServer(function(req, res) {
    res.setHeader('Connection', 'close')
    res.end('Hello Node.js Server!')
})

socket.setKeepAlive() is for TCP Keep-Alive instead of HTTP Keep-Alive, which are two different things. It's very confusing, but TCP Keep-Alive is for keeping an idle connection alive, and HTTP Keep-Alive is for reusing a TCP connection for multiple HTTP requests.

Upvotes: 7

Related Questions