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

I'm writing a multi-tenancy plugin for Payload CMS (

). 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 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 = {
  onInit: async (payload) => {;

    // Move the added middleware up in the stack as far as possible (after
    // "bound dispatch" middleware).
    const router =;
    const index = router.stack.findIndex(
      (layer) => === "bound dispatch"
    router.stack = [
      ...router.stack.slice(0, index + 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