Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling HTTP Keep-Alive in Node.js

Tags:

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.

like image 692
andrzej1_1 Avatar asked Oct 19 '25 14:10

andrzej1_1


1 Answers

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.

like image 122
Shuhei Kagawa Avatar answered Oct 22 '25 02:10

Shuhei Kagawa