This plugin sets up multi-tenancy for your application from within your Admin Panel. It does so by adding a tenant field to all specified collections. Your front-end application can then query data by tenant. You must add the Tenants collection so you control what fields are available for each tenant.
Adds a tenant selector to the admin panel, allowing you to switch between tenants
Filters list view results by selected tenant
Filters relationship fields by selected tenant
Ability to create "global" like collections, 1 doc per tenant
Automatically assign a tenant to new documents
Warning
By default this plugin cleans up documents when a tenant is deleted. You should ensure you have strong access control on your tenants collection to prevent deletions by unauthorized users.
You can disable this behavior by setting cleanupAfterTenantDelete to false in the plugin options.
Installation
Install the plugin using any JavaScript package manager like pnpm, npm, or Yarn:
1
pnpmadd @payloadcms/plugin-multi-tenant
Options
The plugin accepts an object with the following properties:
The plugin scaffolds out everything you will need to separate data by tenant. You can use the tenant field to filter data from enabled collections in your front-end application.
In your frontend you can query and constrain data by tenant with the following:
1
const pagesBySlug =await payload.find({
2
collection:'pages',
3
depth:1,
4
draft:false,
5
limit:1000,
6
overrideAccess:false,
7
where:{
8
// your constraint would depend on the
9
// fields you added to the tenants collection
10
// here we are assuming a slug field exists
11
// on the tenant collection, like in the example above
12
'tenant.slug':{
13
equals:'gold',
14
},
15
},
16
})
NextJS rewrites
Using NextJS rewrites and this route structure /[tenantDomain]/[slug], we can rewrite routes specifically for domains requested:
1
asyncrewrites(){
2
return[
3
{
4
source:'/((?!admin|api)):path*',
5
destination:'/:tenantDomain/:path*',
6
has:[
7
{
8
type:'host',
9
value:'(?<tenantDomain>.*)',
10
},
11
],
12
},
13
];
14
}
React Hooks
Below are the hooks exported from the plugin that you can import into your own custom components to consume.