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

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.