How to identify request (by ID) through middleware chain in Express.

I am developping a RESTful server in node.js, using Express as framework, and Winston, for the moment, as logger module. This server will handle a big amount of simultaneous request, and it would be very useful to me to be able to track the log entries for each specific request, using something like a 'request ID'. The straight solution is just to add this ID as another piece of logging information each time I want to make a log entry, but it will mean to pass the 'request ID' to each method used by the server.

I would like to know if there is any node.js/javascript module or technique that would allow me to do this in an easier way, without carrying around the request ID for each specific request.

If you auto-increment, your later log analytics won't be able to uniquely identify requests, because different instances will generate colliding IDs, and restarting the app will automatically cause ID collisions.

Here's another possible solution.

Install cuid:

npm install --save cuid

Then in your main app file:

var cuid = require('cuid');
var requestId = function requestId(req, res, next) {
  req.requestId = cuid();
  next();
};

// Then, at the top of your middleware:
app.use(requestId);

Now you'll get a friendly request ID that is unlikely to collide, and you'll be able to uniquely identify your requests for your log analytics and debugging, even across multiple instances, and server restarts.

You can use req object that does comes with every request in express.
So the first route you would do in your application would be:

var logIdIterator = 0;

app.all('*', function(req, res, next) {
  req.log = {
    id: ++logIdIterator
  }
  return next();
});

And then anywhere within express, you can access that id in req object: req.log.id;
You will still need to pass some data into functions that do want to create some logs. In fact you might have logging function within req.log object, so that way it will be guaranteed that logging will happen only when there is access to req.log object.