hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.63k stars 65 forks source link

Express Router support #120

Closed ctrlaltdylan closed 3 years ago

ctrlaltdylan commented 3 years ago

I realize this is a very specific ask, but I'm trying to get background queues working with NextJs and the final piece is getting some visibility into the queues withbull-board.

In theory, you'd think you could pull this off:

// pages/api/queues.js
import nc from "next-connect";
const { setQueues, BullAdapter, router, UI } = require("bull-board");
import emailQueue from 'queues/emailQueue';

setQueues([
  new BullAdapter(emailQueue),
]);

const handler = nc()
  .use((req, res, next) => {
    // process.env.HOST === 'domain.com/api'
    req.proxyUrl = process.env.HOST + "/queues";
    next();
  })
  .use(router);

export default handler;

But it's just rendering JSON instead of the web UI. Maybe it's just some incompatibility with express type of middleware?

hoangvvo commented 3 years ago

As mentioned in Twitter PM, it seems like next-connect does not work with Express router (only works with Express middleware now). However, my intention is for it to be able to so I will add a PR soon to add support for this.

hoangvvo commented 3 years ago

I did some work to improve next-connect compatibility with express.js router in v0.10.0.

I also looked at bull-board source code and saw that it tries to add the UI to / which is outside of /api. You would need to explicitly mount it somewhere inside /api such as /api or /api/queue.

const handler = nc().use("/api", router);

Also you need to put that inside pages/api/queues/[[...slug]].js because router will need to be served on other paths (like /api/queues/some/path/, not just /api/queues (see this part in bull-board source code and next-connect doc)

ctrlaltdylan commented 3 years ago

@hoangvvo Thank you!!

I finally got around to experimenting, your update + altering the proxyUrl eventually got me to a working PoC:

https://gist.github.com/ctrlaltdylan/014465155163a7301335c0eea089dfc0