I'm writing a multi-tenancy plugin for Payload CMS (
https://github.com/joas8211/payload-tenancy). Current task is to separate tenants by different base paths. For that I thought writing an Express middleware would make the trick, but it seems to only affect REST API requests and URLs are already rewritten to remove /api. This happens even when setting middleware to config.express.preMiddleware. It seems that there's no way to run middleware before Payload middleware from a plugin, or is there?
I managed to run the middleware before Payload middleware by moving it up the router stack, like so:
const config: Config = {
  ...originalConfig,
  onInit: async (payload) => {
    payload.express.use(createMiddleware());
    // Move the added middleware up in the stack as far as possible (after
    // "bound dispatch" middleware).
    const router = payload.express._router;
    const index = router.stack.findIndex(
      (layer) => layer.name === "bound dispatch"
    );
    router.stack = [
      ...router.stack.slice(0, index + 1),
      ...router.stack.slice(-1),
      ...router.stack.slice(index + 1, -1),
    ];
  },
};Now there's another problem regarding admin front-end. I cannot dynamically decide what base URL it uses for the API. But that's a problem of it's own.
Star
Discord
online
Get dedicated engineering support directly from the Payload team.