Like what we’re doing? Star us on GitHub!

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

Jesse Sivonen
4 weeks ago
2

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.

    Open the post
    Continue the discussion in Discord
    Can't find what you're looking for?
    Get help straight from the Payload team with an Enterprise License.Learn More