Cloud

Multi-Tenancy

Tenant resolution middleware with header, subdomain, JWT, and custom strategies. Rejects unknown, suspended, and archived tenants with 401.

5 min readUpdated DocumentationEdit this page
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

TypeScript
TS
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

StrategySourceExample
headerRequest header named by headerName (lower-cased)x-tenant-id: acme-corp
subdomainFirst label of the Host headeracme.app.io → acme
jwtreq.locals.user.tenantIdPopulated by @axiljs/auth
customYour customResolver(req) functionAny logic you define

Header Strategy (Default)

TypeScript
TS
1app.use(multiTenancy({
2  strategy: 'header',
3  headerName: 'x-tenant-id',
4}))

Subdomain Strategy

TypeScript
TS
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

TypeScript
TS
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 first

Custom Strategy

TypeScript
TS
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.

TypeScript
TS
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.

Situationrequired: true (default)required: false
No tenant ID found401 Tenant identification required (strategy: <strategy>).Continues, no tenant set
ID fails validateTenantId401 Malformed tenant identifier: "<id>".401 (same)
resolveTenant returns null401 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 throwsError 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: the Tenant returned by resolveTenant
  • req.locals.tenantContext: { tenant, resolvedBy }, where resolvedBy is the strategy used
TypeScript
TS
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

TypeScript
TS
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).id

Options Reference

OptionTypeDefaultDescription
strategy'header' | 'subdomain' | 'jwt' | 'custom''header'Resolution method
headerNamestring'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) => booleanLowercase slug, 2–64Format check run before lookup
requiredbooleantrueReject requests with no or unknown tenant
customResolver(req) => string | null | Promise<string | null>—Required when strategy is 'custom'

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY