title: node.js express request Id
body: <p>I'm trying to create some sort of a request Id for logging purposes which will be available to me through every function in the request flow. I want to log every step of the request flow with an Id stating which log line is for which request.</p>
  
  <p>I've looked over some ideas and ran into 2 main suggestions:</p>
  
  <p>The first is creating a middleware that will add a field in the 'req' object like so(as suggested <a href="https://stackoverflow.com/questions/17701796/how-to-identify-request-by-id-through-middleware-chain-in-express">here</a>):</p>
  
  <pre><code>var logIdIterator = 0;
  
  app.all('*', function(req, res, next) {
    req.log = {
      id: ++logIdIterator
    }
    return next();
  });
  </code></pre>
  
  <p>And the second is using <a href="https://www.npmjs.com/package/continuation-local-storage" rel="noreferrer">continuation-local-storage</a></p>
  
  <p>The problems are:</p>
  
  <p>For the first approach - it means I'll have to pass an extra argument to each function in the flow and this is not an easy solution to do over a mature application with countless APIs and flows.</p>
  
  <p>The second one looks promising but unfortunately it has some issues where the state gets lost(see <a href="https://github.com/othiym23/node-continuation-local-storage/issues/29" rel="noreferrer">here</a> for example). 
  Also, it happened a few times when we used our redis library - which is bad because redis requests happen on each of our flows.</p>
  
  <p>I guess if I don't find another solution, I'll have to use the first approach, it's just that I want to avoid passing an extra parameter to thousands of existing functions. </p>
  
  <p>My question is - how do you suggest to maintain a request Id through the request flow?</p>