Multi-tenancy
The same user lives in many workspaces, each with its own feed. Scope any send to one tenant or fan out to many with forTenant — tenant flows into storage, the read API, and per-tenant channel config.
In a multi-tenant app a single user belongs to several workspaces, organizations, or accounts — and each should have its own isolated notification feed. The invoice paid in Acme doesn't belong in the Globex inbox. Multi-tenancy threads a tenant id through every send so storage, the read API, and channel config all stay scoped to the right workspace.
A tenant is just a string id. Single-tenant apps ignore all of this — nothing here is required until you opt in.
Scope a send to a tenant
notifications.forTenant(id) returns the same sending surface (send, sendNow, route, …), with
every delivery scoped to that tenant:
@Injectable()
export class BillingService {
constructor(private readonly notifications: NotificationService) {}
async paid(user: User, invoice: Invoice) {
await this.notifications.forTenant('acme').send(user, new InvoicePaid(invoice));
}
}To deliver the same notification to a user across several workspaces at once, use forTenants — the
send fans out, one delivery (and one storage row) per tenant:
@Injectable()
export class AnnouncementsService {
constructor(private readonly notifications: NotificationService) {}
async broadcast(user: User) {
await this.notifications.forTenants(['acme', 'globex']).send(user, new Announcement());
}
}Or declare the tenant on the notification
When the tenant is part of the event itself, mark a property with @Tenant() instead of threading it
through the call site. The value may be a single id or an array — an array fans out per tenant, just
like forTenants:
import { Notification, Tenant } from '@dudousxd/nestjs-notifications-core';
@Notification({ name: 'invoice.paid' })
export class InvoicePaid {
@Tenant() workspaceId!: string;
// @Tenant() workspaces!: string[]; // delivered once per workspace
}An explicit forTenant(id) / forTenants([...]) always wins; otherwise the @Tenant() property is
read — first on the notification, then on the notifiable. With neither, the send is single-tenant.
The @Tenant() property can also live on the notifiable — useful when a user object already
carries its current workspace.
Tenant flows into storage
The tenant is recorded with each persisted notification. The database channel
writes it as tenantId on the StoredNotification, so the same user's rows are cleanly partitioned
per workspace.
Tenant flows into the read API
The read side mirrors the send side. Scope the query service to a tenant and the feed is isolated:
@Injectable()
export class InboxService {
constructor(private readonly notificationsQuery: NotificationsQueryService) {}
async acmeFeed(user: User) {
const inbox = await this.notificationsQuery.forTenant('acme').unread(user);
const badge = await this.notificationsQuery.forTenant('acme').unreadCount(user);
return { inbox, badge };
}
}NotificationsQueryService.forTenant(id) filters every read (all, unread, unreadCount, …) to
that tenant, so a user signed into Acme never sees Globex's notifications. See
In-app notifications for the full read API.
Follow the request's tenant automatically
If your app sets the tenant of each request with @dudousxd/nestjs-context
(Context.setTenant(...) in your auth guard), the database channel and the inbox can follow it with
no forTenant calls. Turn tenancy on in the context:
@Module({
imports: [
ContextModule.forRoot({ tenancy: { enabled: true } }),
DatabaseChannelModule.forRoot(), // tenancy: 'inherit' by default
],
})
export class AppModule {}With tenancy on:
- A send with no explicit tenant (no
forTenant, no@Tenant()) stores its row with the request's tenant, or with no tenant when the request has none. A queued send keeps the tenant it was sent from. NotificationsQueryServiceand the inbox controller show a request only the rows it may see:
| Request | Row of this tenant | Row of another tenant | Row with no tenant |
|---|---|---|---|
| with a tenant | visible | hidden | hidden (visible with nullRows: 'shared') |
| with no tenant | — | hidden | visible |
inside Context.allTenants(), or with no context | visible | visible | visible |
- Marking read or deleting a row the request can't see answers
404, never403, so ids of other tenants don't leak. - An explicit
forTenant(id)always wins over the request's tenant.
Tenancy only narrows what a request sees. The inbox still scopes every route to the notifiable
resolveRef returns.
Configure it per module with the tenancy option:
DatabaseChannelModule.forRoot({
tenancy: {
enabled: 'inherit', // or true / false; 'inherit' follows ContextModule
kinds: ['organization'], // only these tenant kinds count; others act as no tenant
nullRows: 'shared', // rows with no tenant are visible to every tenant
},
});| Value | Effect |
|---|---|
'inherit' (default) | Follow ContextModule's tenancy.enabled, which is off by default. |
false | Never scope the inbox or stamp rows from the context. |
{ enabled, kinds, family, required, nullRows } | enabled is 'inherit' or a boolean; kinds replaces the context's allow-list; family scopes by a secondary tenant; required overrides the context's tenancy.required; nullRows is 'tenantless' (default) or 'shared'. |
DatabaseChannelModule.forFeature() takes the same option. Without @dudousxd/nestjs-context, or
with tenancy off, nothing changes.
Nested tenants
When the context carries a tenant chain (a clinic with units, say), kinds picks the level the
inbox is scoped by: the most specific level of the chain whose kind is listed. A request running in
a unit reads and stamps the clinic's rows with:
ContextModule.forRoot({ tenancy: { enabled: true } });
// The guard sets the active unit with its chain, root first, the unit last:
// Context.setTenant({
// id: unitId,
// kind: 'unit',
// chain: [{ id: clinicId, kind: 'clinic' }, { id: unitId, kind: 'unit' }],
// })
DatabaseChannelModule.forRoot({ tenancy: { kinds: ['clinic'] } });Without kinds, the inbox follows the active tenant (the unit). To scope by a secondary tenant the
context carries next to the primary one, set family, e.g. tenancy: { family: 'patient' }.
A queued send keeps the whole chain it was sent from, so the worker stamps the same level.
Require a tenant
With tenancy.required on in ContextModule, an inbox read or mutation from a request with no
tenant answers 403 (E_TENANT_REQUIRED) instead of showing the tenantless rows. Set required in
the module's tenancy option to override it for the inbox alone (required: true turns it on for
the inbox only, required: false turns it off).
Sends never require a tenant: a sender, queue or worker with no tenant stores the row with no
tenant, as before. forTenant(id) and code outside a request (a worker, a cron) are not affected.
Nested tenants, families and required need @dudousxd/nestjs-context 2.1 or later. An older
context ignores them and scopes by the flat tenant.
Rows with no tenant are filtered in memory rather than in the store query, so with
nullRows: 'shared', or for a request with no tenant, paginate and unreadCount load the
notifiable's rows before slicing or counting, and markAllAsRead loads the unread rows and marks
the visible ones one by one.
Per-tenant channel config
Channels can resolve their transport or options per tenant, so each workspace sends through its own provider, credentials, or endpoint. When a delivery runs with a tenant scope, the channel calls your resolver with the tenant id:
- Transport resolvers —
resolveTransport(tenant)on sms and push. For mail,@nestjs/mailowns the transport: give it aTenantRoutingMailTransport. - Options resolvers —
resolveOptions(tenant)on slack and webhook.
SmsChannelModule.forRoot({
from: '+15555550100',
resolveTransport: (tenant) => tenantSmsTransports.get(tenant) ?? defaultTransport,
});Sends with no tenant scope keep using the channel's default config, so the resolver is purely additive.
The result carries the tenant
Every SendResult reports the tenant it was scoped to, so a fan-out tells you which workspace each
delivery belongs to:
@Injectable()
export class AnnouncementsService {
constructor(private readonly notifications: NotificationService) {}
async broadcast(user: User) {
const results = await this.notifications
.forTenants(['acme', 'globex'])
.send(user, new Announcement());
return results.map((r) => r.tenant); // ['acme', 'globex']
}
}tenant is undefined for single-tenant sends. Each entry still carries its per-channel
results.
How the tenant travels under the hood
The tenant rides along on a DeliveryContext passed to each channel's send(). Async dispatch
carries it too — the queued NotificationJob includes the tenant, so a notification delivered on a
worker stays scoped to the same workspace it was sent for.
Async dispatch
How a notification and its recipient survive the trip to a worker — notifications serialize to { name, data }, notifiables to a { type, id } reference rebuilt by resolveNotifiable.
Context capture (causer attribution)
Capture who triggered a notification — the causer, tenant, and trace id — at send() time and thread it through lifecycle events, the async carrier, and the database row. Integrates @dudousxd/nestjs-context; degrades to a no-op when it's absent.