Created
February 15, 2022 03:36
-
-
Save Keith-Hon/ed48526c3d9a249d5d56048df6172762 to your computer and use it in GitHub Desktop.
Github webhook handler for Next.js
This file contains hidden or 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
// pages/api/webhooks/github.js | |
const { exec } = require("child_process"); | |
const crypto = require("crypto"); | |
// Handle GitHub Webhooks | |
export default function handler(req, res) { | |
try { | |
console.log("Incoming Request"); | |
if (req.method !== 'POST') { | |
res.send(404); | |
return; | |
} | |
let sig = | |
"sha256=" + | |
crypto | |
.createHmac("sha256", process.env.WEBHOOKS_SECRET) | |
.update(JSON.stringify(req.body)) | |
.digest("hex"); | |
if ( | |
req.headers["x-hub-signature-256"] === sig && | |
req.body?.ref === "refs/heads/main" && | |
process.env.REPO_PATH | |
) { | |
exec( | |
"cd " + | |
process.env.REPO_PATH + | |
" && git pull && npm install && npm run build && pm2 restart app" | |
); | |
console.log("GitHub Webhook ran successfully"); | |
res.end(); | |
return; | |
} | |
console.log("GitHub Webhook failed"); | |
res.end(); | |
return; | |
} catch (e) { | |
console.log(e); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment