Search code examples
node.jssails.jskeep-alive

Keep-Alive in SailsJs


I would like to disable the keep-alive for TCP connections coming from load balancer to my sailsjs server. So basically I would like to turn off the HTTP keep-alive. Right now my server responds with header

connection →keep-alive

I was wondering if there is a specific setting I need to tweak in the sails server to make this go away?


Solution

  • From the sails side you have two options, both include setting a HTTP header to close the connection instead of the default keep-alive .

    Option 1: Set the header at controller level by adding the code below before your actual response. This gives greater control as you can decide which specific controller closes the connection:

    res.set("Connection", "close");
    

    Option 2: Alternatively, you can set the header at middleware level for all connections.

    To do this, open config/http.js, create a new function inside the middleware object to set the header eg. setHeaderClose, then uncomment the order array and add a reference to the above function.

    order: [
        'setHeaderClose',
        'startRequestTimer',
        'cookieParser',
        'session',
        'myRequestLogger',
        'bodyParser',
        'handleBodyParserError',
        'compress',
        'methodOverride',
        'poweredBy',
        '$custom',
        'router',
        'www',
        'favicon',
        '404',
        '500'
    ],
    
    setHeaderClose: function(req, res, next) {
        res.set("Connection", "close");
        next();
    }