Node Express specific timeout value per route

Easy way to increase timeout on a route:

app.post('/some_route', (req, res) => {
   req.setTimeout(60 * 1000); //use req. this sets timeout to 60 seconds
});

OR

If you wanted to increase the timeout on the server for all routes, you can edit your app.js:

var serverApp = app.listen();
serverApp.setTimeout(60 * 1000); //use sets timeout to 60 seconds

Obviously, use the server setting sparingly. You don't want to tie up your server with long requests, so most of the time using the route specific timeouts is better architecture..


I've solved it using the following route configuration:

'use strict';

const ms = require('ms');
const express = require('express');
const router = express.Router();

router.route('/upload-files')
  .post(
    setConnectionTimeout('12h'),
    require('./actions/upload-files').responseHandler
  );

function setConnectionTimeout(time) {
  var delay = typeof time === 'string'
    ? ms(time)
    : Number(time || 5000);

  return function (req, res, next) {
    res.connection.setTimeout(delay);
    next();
  }
}

exports.router = router;

Where the key logic is the following middleware:

  function (req, res, next) {
    res.connection.setTimeout(delay);
    next();
  }

I hope this reference will come in handy for others.