使用NextJs实现Github Webhook

4

我正在处理一个NextJS项目,并希望使用Github Webhook部署包含部署指令的脚本。

我已在Github上设置了一个Push Webhook。

我尝试将以下代码添加到我的server.ts文件中,目前使用ngrok进行测试:

// testing
server.post("/webhooks/github", function(req, res) {
  var sender = req.body.sender;
  var branch = req.body.ref;

  if (branch.indexOf("master") > -1 && sender.login === githubUsername) {
    deploy(res);
  }
});

function deploy(res: any) {
  childProcess.exec("sh deploy.sh", function(err, stdout, stderr) {
    if (err) {
      console.error(err, stderr);
      return res.send(500);
    }
    console.log(stdout);
    res.send(200);
  });
}

这个文件是我NextJS应用程序中的Node文件。

但是,在我的ngrok日志中出现了502错误。

我想知道在我的NextJS应用程序中应该把这个Webhook端点放在哪里才能使其正常工作。

2个回答

2

我能让这个工作的唯一方法是在同一台服务器上创建另一个应用程序(我使用了express),然后使用该应用程序上的端点作为github webhook,从那里运行部署脚本。

这是一个简单的解决方案,希望这能帮助到某些人。


0

我知道有点晚了,但这对我很有效:

// 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);
    }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接