expresscorsprobot

How can I access the Express app instance to set CORS origin in a Probot app?


The probot documentation mentions that I can use routes just like I would in a vanilla Express server.

I wantr to set CORS origin headers for these routes. In a vanilla Express server I would use the cors package:

const cors = require('cors')

...

app.use(cors())

But the probot app does not have the function use.

module.exports = app => {
  app.use(cors(corsOptions));
// ...

causes the error:

ERROR (event): app.use is not a function
    TypeError: app.use is not a function

How do I set CORS?


Solution

  • You must start the app programmatically. This way you can access the Express app AFTER probot loads but BEFORE Probot starts running:

    const cors = require("cors");
    const bodyParser = require("body-parser");
    const { Probot } = require("probot");
    const { corsOptions } = require("./src/util/init-server.js");
    const endpoint = require("./src/controller/endpoint");
    const { handleWhatever } = require("./src/controller/controller");
    
    
    // https://github.com/probot/probot/blob/master/src/index.ts#L33
    const probot = new Probot({
      id: process.env.APP_ID,
      port: process.env.PORT,
      secret: process.env.WEBHOOK_SECRET,
      privateKey: process.env.PRIVATE_KEY,
      webhookProxy: process.env.WEBHOOK_PROXY_URL,
    });
    
    
    const probotApp = app => {
      /** Post a comment on new issue */
      app.on("issues.opened", async context => {
        const params = context.issue({ body: "Hello World!" });
        return context.github.issues.createComment(params);
      });
    
      /** --- Express HTTP endpoints --- */
      const router = app.route("/api");
      router.use(cors(corsOptions)); // set CORS here
      router.use(bodyParser.json());
      router.use(bodyParser.urlencoded({ extended: true }));
      // router.set("trust proxy", true);
      // router.use(require('express').static('public')); // Use any middleware
      router.get("/ping", (req, res) => res.send("Guten Tag! " + new Date()));
      router.post(endpoint.handleWhatever , handleWhatever );
    };
    
    
    /** --- Initialize Express app by loading Probot --- */
    probot.load(probotApp);
    
    /* ############## Express instance ################ */
    const app = probot.server;
    const log = probot.log;
    app.set("trust proxy", true);
    
    /** --- Run Probot after setting everything up --- */
    Probot.run(probotApp);
    

    Here some GitHub issues and docs that helped me answer my question: