Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Rewriting base path to dynamically to section admin and API endpoints for different tenants

default discord avatar
jessesivonen2 years ago

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 on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get dedicated engineering support directly from the Payload team.