X-Hub-Signature Verification on Google Cloud Functions / Firebase Cloud Functions for Facebook Graph API Webhooks

Google Cloud Functions (GCF) / Firebase Cloud Functions automatically parses the request body for all requests where content type is application/json. Converting the parsed request body to a string via JSON.stringify() always fails the X-Hub-Signature verification for Facebook Graph API webhooks. And as of today, there is no way to plug in any middleware into the Express pipeline to get access to the raw request body. Fortunately, the folks at Google added a new rawBody property to the request object to fix this problem. Below code has been tested and works with Facebook Graph API webhooks. All you have to do is pass req.rawBody to the update method on the Hmac object instead of JSON.stringify(req.body).

Resources:

  1. https://stackoverflow.com/questions/42950561/how-can-i-get-the-raw-request-body-in-a-google-cloud-function
  2. https://issuetracker.google.com/issues/36252545
  3. https://cloud.google.com/functions/docs/writing/http#handling_http_requests_file_uploads
  4. https://cloud.google.com/community/tutorials/github-auto-assign-reviewers-cloud-functions#validating-the-request-from-github

Happy Coding!