Skip to content

Tenant Extractors ​

Five built-in extractors cover common identifier sources. Extraction finds an identifier; validation checks its format, and your application authorizes the caller's access to that tenant. The default HTTP validator accepts UUID-shaped strings. Use a custom validator for slugs.

Header (default) ​

typescript
TenancyModule.forRoot({
  tenantExtractor: 'X-Tenant-Id', // shorthand for HeaderTenantExtractor
})

A client-controlled header is not proof of tenant membership. Authenticate first and check the resolved tenant against the authenticated principal.

Subdomain ​

typescript
import { SubdomainTenantExtractor } from '@nestarc/tenancy';

TenancyModule.forRoot({
  tenantExtractor: new SubdomainTenantExtractor({
    excludeSubdomains: ['www', 'api'], // optional, defaults to ['www']
  }),
  validateTenantId: (id) => /^[a-z0-9-]+$/.test(id),
})
// tenant1.app.com → 'tenant1'

Uses the psl dependency for ccTLD parsing. Format validation does not check tenant existence or membership.

JWT Claim ​

typescript
import { JwtClaimTenantExtractor } from '@nestarc/tenancy';

TenancyModule.forRoot({
  tenantExtractor: new JwtClaimTenantExtractor({
    claimKey: 'org_id',
    headerName: 'authorization', // default
  }),
})
// Authorization: Bearer eyJ... → decoded payload.org_id

The extractor decodes the JWT payload. When exp or nbf is numeric, it checks the timestamp in seconds and returns null if the token has expired or is not yet valid. Absent or nonnumeric time claims are skipped. Have your authentication middleware verify the same token's signature, issuer, audience, and required claims before extraction. Authorize the selected tenant against the verified principal.

Authentication before tenant extraction ​

Register authentication with app.use() before calling app.init() or app.listen(). Nest runs the tenant middleware and its lifecycle hooks before Guards, so a Passport AuthGuard cannot supply the verified user at extraction time. The 0.16.5 extractor documentation and the JWT example generated by tenancy init both describe this ordering. JWT extractor in 0.16.5

This Express bootstrap fragment assumes your authenticate middleware verifies the token and populates req.user before calling next(); unauthenticated requests must be rejected there.

typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { authenticate } from './auth.middleware';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(authenticate);
  await app.listen(3000); // initializes module middleware after app.use()
}
void bootstrap();

Read custom properties through a checked shape, because the public hook request uses unknown for adapter-specific fields:

typescript
import { ForbiddenException } from '@nestjs/common';
import { TenancyModule } from '@nestarc/tenancy';

TenancyModule.forRoot({
  tenantExtractor: 'X-Tenant-Id',
  onTenantResolved: (tenantId, request) => {
    const user = request.user;
    if (
      typeof user !== 'object' || user === null ||
      !('org_id' in user) || user.org_id !== tenantId
    ) {
      throw new ForbiddenException('Tenant mismatch');
    }
  },
});

The hook authorizes the tenant selected by the header against the user authenticated during bootstrap. The runnable example includes the bootstrap sequence, credentials, and tenant membership checks. Runnable HTTP example

Path Parameter ​

typescript
import { PathTenantExtractor } from '@nestarc/tenancy';

TenancyModule.forRoot({
  tenantExtractor: new PathTenantExtractor({
    pattern: '/api/tenants/:tenantId/resources',
    paramName: 'tenantId',
  }),
  validateTenantId: (id) => /^[a-z0-9-]+$/.test(id),
})
// /api/tenants/acme/resources → 'acme'

From 0.16.1, the extractor prefers request.path and falls back to request.url when the path is absent or empty. Query strings and fragments are removed before matching. This supports path extraction from a raw Node request; authentication, cookies, and response methods still depend on the HTTP adapter and middleware.

If you must remain on 0.16.0, normalize the raw URL into path with this compatibility wrapper:

typescript
import { PathTenantExtractor, TenancyModule } from '@nestarc/tenancy';

const pathExtractor = new PathTenantExtractor({
  pattern: '/api/tenants/:tenantId/resources',
  paramName: 'tenantId',
});

TenancyModule.forRoot({
  tenantExtractor: {
    extract(request) {
      return pathExtractor.extract({
        ...request,
        path: (request.path || request.url || '').split(/[?#]/, 1)[0],
      });
    },
  },
  validateTenantId: (id) => /^[a-z0-9-]+$/.test(id),
});

Composite (Fallback Chain) ​

typescript
import {
  CompositeTenantExtractor,
  HeaderTenantExtractor,
  SubdomainTenantExtractor,
} from '@nestarc/tenancy';

TenancyModule.forRoot({
  tenantExtractor: new CompositeTenantExtractor([
    new HeaderTenantExtractor('X-Tenant-Id'),
    new SubdomainTenantExtractor(),
  ]),
  validateTenantId: (id) => /^[a-z0-9-]+$/.test(id),
})
// First non-null result wins; accepts slug identifiers from either source.

The chain falls back only when extraction returns null. An invalid first result fails validation; it does not retry later extractors. Choose one identifier format across the chain and authorize the selected result.

Custom Extractor ​

An HttpOnly session cookie can identify the signed-in user. A separate tenant_id cookie records the user's selection. In this Express example, the application's verifySession() validates the session credential and returns trusted allowedTenantIds for that user, or null for an invalid or expired session.

typescript
import type { NextFunction, Request, Response } from 'express';
import type { TenantExtractor } from '@nestarc/tenancy';
import { verifySession } from './sessions';

export async function authenticateTenantSession(
  request: Request & { authorizedTenantId?: string },
  response: Response,
  next: NextFunction,
): Promise<void> {
  try {
    const cookies: Record<string, unknown> = request.cookies ?? {};
    const session = typeof cookies.session === 'string'
      ? await verifySession(cookies.session)
      : null;
    if (!session) {
      response.sendStatus(401);
      return;
    }

    const tenantId = typeof cookies.tenant_id === 'string' ? cookies.tenant_id : null;
    if (!tenantId || !session.allowedTenantIds.includes(tenantId)) {
      response.sendStatus(403);
      return;
    }
    request.authorizedTenantId = tenantId;
  } catch (error) {
    next(error);
    return;
  }
  next();
}

export const cookieTenantExtractor: TenantExtractor = {
  extract(request) {
    const id = request.authorizedTenantId;
    return typeof id === 'string' ? id : null;
  },
};

Configure TenancyModule.forRoot({ tenantExtractor: cookieTenantExtractor }). At bootstrap, register the application's cookie parser with app.use(), then register app.use(authenticateTenantSession) before calling app.init() or app.listen(). The extractor receives the ID that passed membership authorization. The module still validates its format.

Documentation site: MIT License. Check each package for its license.