Multi-Tenancy
Tenant resolution middleware with header, subdomain, JWT, and custom strategies. Rejects unknown, suspended, and archived tenants with 401.
On this page12
Overview
multiTenancy() resolves the current tenant from each request, validates the
tenant ID, looks up the full tenant record, rejects tenants that are unknown,
suspended, or archived, and attaches the result to req.locals.tenant. It keeps
no process state, so it is safe to run on many instances.
Basic Usage
1import { multiTenancy, getTenant, getTenantId } from '@axiljs/cloud'
2
3app.use(multiTenancy({
4 strategy: 'header',
5 headerName: 'x-tenant-id',
6 resolveTenant: async (id) => await db.tenants.findById(id), // Tenant | null
7 required: true,
8}))
9
10app.get('/api/data', (req, res) => {
11 const tenant = getTenant(req)
12 res.success({ tenantId: tenant.id, plan: tenant.plan })
13})Warning
If you omit resolveTenant, the default resolver returns an active stub
({ id, name: 'Tenant <id>', status: 'active' }) for any well-formed ID.
Nothing is looked up, so every syntactically valid tenant is accepted. Always
supply resolveTenant in production.
Resolution Strategies
| Strategy | Source | Example |
|---|---|---|
header | Request header named by headerName (lower-cased) | x-tenant-id: acme-corp |
subdomain | First label of the Host header | acme.app.io → acme |
jwt | req.locals.user.tenantId | Populated by @axiljs/auth |
custom | Your customResolver(req) function | Any logic you define |
Header Strategy (Default)
1app.use(multiTenancy({
2 strategy: 'header',
3 headerName: 'x-tenant-id',
4}))Subdomain Strategy
1app.use(multiTenancy({
2 strategy: 'subdomain',
3 // acme.app.example.com → tenantId = 'acme'
4}))The port is stripped before parsing. The host must have at least three labels
(tenant.example.com), so localhost and example.com yield no tenant. IPv4
and IPv6 hosts (for example 10.0.0.5 or [::1]:3000) never carry a tenant.
JWT Strategy
1import { JWT, authenticate } from '@axiljs/auth'
2
3const jwt = new JWT(process.env.JWT_SECRET!)
4
5app.use(authenticate(jwt))
6app.use(multiTenancy({ strategy: 'jwt' }))
7// Reads req.locals.user.tenantId, so authenticate() must run firstCustom Strategy
1app.use(multiTenancy({
2 strategy: 'custom',
3 customResolver: async (req) => {
4 const apiKey = req.headers['x-api-key']
5 const org = await lookupOrgByApiKey(apiKey)
6 return org?.id ?? null
7 },
8}))customResolver may return a string, null, or a promise of either. If
strategy is 'custom' and no customResolver is given, the middleware passes
a plain Error to next(), which the default error handler turns into a 500.
Tenant Validation
Tenant IDs are checked before resolveTenant is called. The default validator
accepts 2 to 64 characters of lowercase letters, digits, and hyphens that start
and end with a letter or digit. Pass validateTenantId for UUIDs or other
formats.
1app.use(multiTenancy({
2 strategy: 'header',
3 validateTenantId: (id) => /^[0-9a-f-]{36}$/.test(id),
4 resolveTenant: async (id) => db.tenants.findById(id),
5}))Rejection Behavior
Every rejection is an UnauthorizedError from @axiljs/common: HTTP 401,
error code UNAUTHORIZED. With the default error handler the response body is
{ "error": { "code": "UNAUTHORIZED", "message": "..." } } (plus stack
outside production).
Warning
Changed in 0.3.3: unknown, suspended, and archived tenants are all rejected
with 401 (UNAUTHORIZED), before any later route or auth middleware runs.
Older source comments described suspended and archived tenants as 403. If a
client or test expects 403 here, update it to 401.
| Situation | required: true (default) | required: false |
|---|---|---|
| No tenant ID found | 401 Tenant identification required (strategy: <strategy>). | Continues, no tenant set |
ID fails validateTenantId | 401 Malformed tenant identifier: "<id>". | 401 (same) |
resolveTenant returns null | 401 Unknown tenant: "<id>". | Continues, no tenant set |
Tenant status is 'suspended' | 401 Tenant "<id>" is suspended. | 401 (same) |
Tenant status is 'archived' | 401 Tenant "<id>" has been archived. | 401 (same) |
resolveTenant or customResolver throws | Error passed to next(err) | Same |
Only 'suspended' and 'archived' are rejected; any other status proceeds.
Request Context
On success the middleware sets:
req.locals.tenant: theTenantreturned byresolveTenantreq.locals.tenantContext:{ tenant, resolvedBy }, whereresolvedByis the strategy used
1interface Tenant {
2 id: string
3 name: string
4 status: 'active' | 'suspended' | 'archived'
5 plan?: 'free' | 'pro' | 'enterprise'
6 metadata?: Record<string, unknown>
7}Helper Functions
1import { getTenant, getTenantId } from '@axiljs/cloud'
2
3const tenant = getTenant(req) // throws UnauthorizedError (401) if no tenant is attached
4const id = getTenantId(req) // shorthand for getTenant(req).idOptions Reference
| Option | Type | Default | Description |
|---|---|---|---|
strategy | 'header' | 'subdomain' | 'jwt' | 'custom' | 'header' | Resolution method |
headerName | string | 'x-tenant-id' | Header read by the header strategy |
resolveTenant | (id: string) => Promise<Tenant | null> | Active stub (see above) | Database or cache lookup |
validateTenantId | (id: string) => boolean | Lowercase slug, 2–64 | Format check run before lookup |
required | boolean | true | Reject requests with no or unknown tenant |
customResolver | (req) => string | null | Promise<string | null> | — | Required when strategy is 'custom' |
Was this page helpful?