Search code examples
javascriptnode.jsexpresswebhooks

webhooks of octokit are not working when i am using them through the express server


I have created a webhook handler using the octokit but the webhook server is not when when using it through the express server. Although the docs of the octokit mention that it supports the web server but for me its returns the response 202

although If instead of express server I create their own server then it start working with response code 200 ex:

const middleware = createNodeMiddleware(app.webhooks, { path });

// This creates a Node.js server that listens for incoming HTTP requests (including webhook payloads from GitHub) on the specified port. When the server receives a request, it executes the `middleware` function that you defined earlier. Once the server is running, it logs messages to the console to indicate that it is listening.
http.createServer(middleware).listen(port, () => {
  console.log(`Server is listening for events at: ${localWebhookUrl}`);
  console.log("Press Ctrl + C to quit.");
});

This doesn't work when I wrap In express server no console nothing.

import express, { Request, Response } from "express";
import dotenv from "dotenv";
import { createNodeMiddleware } from "@octokit/webhooks";
import fs from "fs";
import { App } from "@octokit/app";
dotenv.config();

const PORT = process.env.PORT || 8000;
const expressApp = express();
const appId = process.env.APP_ID ?? "";
const webhookSecret = process.env.WEBHOOK_SECRET ?? "";
const privateKeyPath = process.env.PRIVATE_KEY_PATH ?? "";

// This reads the contents of your private key file.
const privateKey = fs.readFileSync(privateKeyPath, "utf8");
const octokitApp = new App({
  appId,
  privateKey,
  webhooks: { secret: webhookSecret },
});
expressApp.use(express.json());
const middleware = createNodeMiddleware(octokitApp.webhooks, {
  path: "/api/webhook",
});
expressApp.use(middleware);

octokitApp.webhooks.onAny(() => {
  console.log(`first`);
});
octokitApp.webhooks.on("pull_request.reopened", () => console.log(`first`));

expressApp.get("/", (req: Request, res: Response) => {
  return res.status(200).json({
    message: "Hello world",
  });
});
expressApp.listen(PORT, () => console.log(`Server is running at port ${PORT}`));


Solution

  • I was able to solve this locally by removing app.use(express.json())