Last active
May 18, 2021 17:06
-
-
Save dipanshuchaubey/35e6778aab3f4efa47eefd6f54acacf7 to your computer and use it in GitHub Desktop.
How to setup Github Webhooks using Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto') | |
const express = require('express') | |
const bodyParser = require('body-parser') | |
const app = express() | |
// To include rawBody in req parameter | |
app.use(bodyParser.json({ | |
verify: (req, res, buf) => { | |
req.rawBody = buf | |
} | |
})) | |
app.post('/github', (req, res) => { | |
const secret = "YOUR_SECRET_HERE" | |
const signature = Buffer.from('sha256=' + crypto | |
.createHmac('sha256', secret) | |
.update(req.rawBody) | |
.digest('hex'), 'utf-8') | |
// For secure compare use a secure comaprision method | |
if(signature.length !== req.headers['x-hub-signature-256'].length || | |
req.headers['x-hub-signature-256'] !== signature.toString()){ | |
console.log("Invalid Signature"); | |
return res.status(401).end(); | |
} | |
return res.status(200).send('Authentication complete') | |
}) | |
app.listen(5000, () => console.log("Server running on port 5000")) | |
/** | |
References | |
1. https://www.digitalocean.com/community/tutorials/how-to-use-node-js-and-github-webhooks-to-keep-remote-projects-in-sync | |
2. https://docs.github.com/en/developers/webhooks-and-events/creating-webhooks | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment