title: Node.js HTTP streaming request vs. Express.js request object
body: <p>This is a classic tale of "if it ain't broke, don't fix it"</p>
  
  <p>I had created a relatively simple HTTP request handler using Node.js. I am authenticating the request by matching the SHA-1 of the request body to a signature that comes as a request header:</p>
  
  <pre><code>var http = require('http');
  var crypto = require('crypto');
  var secret = process.env.MY_SECRET;
  
  var requestListener = function(req, res) {
      if (req.method === 'POST') {
          var body = '';
          req.on('data', function(data) {
              body += data;
          });
          req.on('end', function() {
              var signature = req.headers['x-signature'];
              var hash = crypto.createHmac('sha1', secret)
                  .update(body)
                  .digest('hex')
                  .toUpperCase();
              if (signature === hash) {
                  // request is authorized
              }
          });
      }
  };
  
  var server = http.createServer(requestListener);
  server.listen(3000);
  </code></pre>
  
  <p>This worked fine, except everything is ugly and there were other features of Express.js I wanted to implement anyways. I rewrote the code as follows:</p>
  
  <pre><code>var crypto = require('crypto');
  var express = require('express');
  var app = express();
  var secret = process.env.MY_SECRET;
  
  app.use(function(req, res, next) {
      var signature = req.get('x-signature');
  
      var hash = crypto.createHmac('sha1', secret)
          .update(req.body)
          .digest('hex')
          .toUpperCase();
  
      if (signature === hash) {
          next();
      } else {
          // unauthorized
      }    
  });
  
  app.post('/', function(req, res) {
      // request is authorized
  });
  
  app.listen(3000);
  </code></pre>
  
  <p>Of course, the crypto method wouldn't run because <code>req.body</code> is now neither a string or a Buffer. But how do I fix this?</p>
  
  <p>I included some middleware:</p>
  
  <pre><code>app.use(bodyParser.json());
  </code></pre>
  
  <p>Then used <code>JSON.stringify</code> to convert the result in to a string. This allows the crypto method to run, however, the hash and the signature did not match!</p>
  
  <p>Is it possible that Express is doing something else to the request body when using middleware like body-parser? This doesn't make any sense to me, but perhaps I am missing something.</p>