Skip to content

Getting Started ​

Build a working multi-tenant API endpoint in 5 minutes.

Not sure which module to adopt first? Start with the package comparison or the Adoption Roadmap.

Prerequisites ​

ToolVersion
Node.js^22.23.4 or ^24.22.1
NestJS10 or 11
Prisma7 recommended; 6 supported by tenancy
PostgreSQL14+

These prerequisites cover tenancy 0.16.4 and standalone audit-log 0.9.0; use the intersection of every installed package's runtime and peer ranges. Verify the actual Node runtime and the application's HTTP parser dependencies before deployment; see the 0.16.2 security upgrade.

Already configured these dependencies?

Skip to Step 2 only if @nestarc/tenancy, the Prisma 7 PostgreSQL adapter, prisma.config.ts, and the generated client are already in place.

Step 1: Install ​

bash
npm install @nestarc/[email protected] @prisma/client @prisma/adapter-pg pg dotenv
npm install --save-dev prisma

This quick start assumes the generated client and prisma.config.ts are configured as shown in Prisma 7 Setup.

Step 2: Enable RLS ​

This example assumes an existing, empty users table that matches the model below except for tenant_id. Add the tenant column, index, and Row Level Security as the schema owner:

sql
ALTER TABLE users ADD COLUMN tenant_id TEXT NOT NULL;
CREATE INDEX users_tenant_id_idx ON users (tenant_id);

ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE users FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON users
  USING (tenant_id = current_setting('app.current_tenant', true)::text);

CREATE POLICY tenant_context_guard_users ON users
  AS RESTRICTIVE
  USING (NULLIF(current_setting('app.current_tenant', true), '') IS NOT NULL)
  WITH CHECK (NULLIF(current_setting('app.current_tenant', true), '') IS NOT NULL);

Expose the same table in your Prisma schema, then regenerate the client:

prisma
model User {
  id       String @id @default(uuid())
  name     String
  tenantId String @map("tenant_id")

  @@index([tenantId], map: "users_tenant_id_idx")
  @@map("users")
}
bash
npx prisma generate

If you use Prisma Migrate, put the column, index, and RLS statements in the same migration instead of applying them as ad-hoc SQL.

Existing production rows

ADD COLUMN ... NOT NULL only succeeds on an empty table. For an existing table, add a nullable column, backfill every row from a trusted tenant-ownership source, verify the mapping, and only then apply NOT NULL. Do not assign unrelated rows to a single fallback tenant.

WARNING

Both ENABLE and FORCE are required. Without FORCE, the table owner role bypasses RLS entirely. See 5 Common Multi-Tenancy Pitfalls for details.

Step 3: Register the Module ​

typescript
// app.module.ts
import { Module } from '@nestjs/common';
import { TenancyModule } from '@nestarc/tenancy';
import { PrismaService } from './prisma.service';
import { UsersController } from './users/users.controller';
import { UsersService } from './users/users.service';

@Module({
  imports: [
    TenancyModule.forRoot({
      tenantExtractor: 'X-Tenant-Id',
    }),
  ],
  controllers: [UsersController],
  providers: [PrismaService, UsersService],
})
export class AppModule {}

Authenticate tenant selection in production

The raw X-Tenant-Id header keeps this local example short, but it does not prove that a caller may access that tenant. In production, derive the tenant from an authenticated JWT claim or cross-check the header against one.

Step 4: Extend Prisma ​

typescript
// prisma.service.ts
import 'dotenv/config';
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client';
import { TenancyService, createPrismaTenancyExtension } from '@nestarc/tenancy';

@Injectable()
export class PrismaService implements OnModuleInit {
  public readonly client;

  constructor(private readonly tenancyService: TenancyService) {
    const adapter = new PrismaPg({
      connectionString: process.env.DATABASE_URL!,
    });
    const basePrisma = new PrismaClient({ adapter });
    this.client = basePrisma.$extends(
      createPrismaTenancyExtension(tenancyService, {
        autoInjectTenantId: true,
        // Use the Prisma field name; @map("tenant_id") handles the SQL column.
        tenantIdField: 'tenantId',
      }),
    );
  }

  async onModuleInit() {
    await this.client.$connect();
  }
}

Run migrations and RLS setup with a schema-owner credential, but connect the application through a separate non-owner, non-superuser role. Have a database administrator or provisioning process run CREATE ROLE (it requires PostgreSQL CREATEROLE or superuser privilege); the migration owner can then apply the grants:

sql
CREATE ROLE app_user LOGIN PASSWORD 'replace-with-a-secret';
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE users TO app_user;

Set the runtime DATABASE_URL to that role (for example, postgresql://app_user:...@localhost:5432/app). Keep schema-owner credentials out of the running application.

For separate credentials, point prisma.config.ts at env('MIGRATION_DATABASE_URL') and keep the adapter above on DATABASE_URL. The former owns schema migrations; the latter is the restricted runtime connection.

Step 5: Create an API Endpoint ​

typescript
// users/users.service.ts
import { Injectable } from '@nestjs/common';
import { TenancyService } from '@nestarc/tenancy';
import { PrismaService } from '../prisma.service';

@Injectable()
export class UsersService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenancy: TenancyService,
  ) {}

  findAll() {
    // RLS automatically filters by tenant — no manual WHERE clause needed
    return this.prisma.client.user.findMany();
  }

  create(name: string) {
    const tenantId = this.tenancy.getCurrentTenantOrThrow();
    return this.prisma.client.user.create({ data: { name, tenantId } });
  }
}

Prisma's generated UserCreateInput still requires tenantId at compile time, so the service supplies the resolved tenant context rather than accepting it from the request body. The extension overwrites the same field at runtime to prevent body-level spoofing and also covers bulk write paths. In production, authenticate or cross-check that resolved context as described above.

typescript
// users/users.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  findAll() {
    return this.usersService.findAll();
  }

  @Post()
  create(@Body('name') name: string) {
    return this.usersService.create(name);
  }
}

Step 6: Test It ​

bash
# Create a user as tenant A
curl -X POST http://localhost:3000/users \
  -H "X-Tenant-Id: 550e8400-e29b-41d4-a716-446655440000" \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice"}'

# Create a user as tenant B
curl -X POST http://localhost:3000/users \
  -H "X-Tenant-Id: 123e4567-e89b-42d3-a456-426614174000" \
  -H "Content-Type: application/json" \
  -d '{"name": "Bob"}'

# Query as tenant A — only sees Alice
curl http://localhost:3000/users \
  -H "X-Tenant-Id: 550e8400-e29b-41d4-a716-446655440000"
# => [{"id":"<uuid>","name":"Alice","tenantId":"550e8400-e29b-41d4-a716-446655440000"}]

# Query as tenant B — only sees Bob
curl http://localhost:3000/users \
  -H "X-Tenant-Id: 123e4567-e89b-42d3-a456-426614174000"
# => [{"id":"<uuid>","name":"Bob","tenantId":"123e4567-e89b-42d3-a456-426614174000"}]

With the RLS policy and application role configured as above, PostgreSQL filters queries by the current tenant without a manual application-level WHERE clause. If either request returns both users or no rows, check the database role, RLS policy, and tenant context.

What's Next? ​

5 min — Standardize your API responses

Add @nestarc/safe-response to auto-wrap all responses with consistent error codes, pagination metadata, and Swagger schemas. Quick Start →

Add your first audit record

Start with one business event or one tracked Prisma model, then verify the actor, tenant, changed values, and rollback. Audit-log 0.9.0 supports managed manual transactions, opt-in input validation, diagnostics, and SQL Server history queries. Run the 0.9.0 example → · Add to an existing app →. For durable audit delivery after commit, see Atomic Outbox Delivery.

30 min — Full tutorial

Build a complete multi-tenant task management API with tenancy + safe-response + testing. Full Tutorial →

See the package comparison and Adoption Roadmap for the recommended adoption path.

Stack Overview ​

nestarc packages compose through NestJS modules, Prisma integrations, and explicit transport boundaries:

Your NestJS App
|-- Request/API layer: safe-response, pagination, idempotency, api-keys
|-- Domain/data layer: tenancy, audit-log, soft-delete, feature-flag, rbac
|-- Events/workers: outbox, inbox, webhook, data-subject, jobs
`-- PostgreSQL + Prisma
PackageRole
@nestarc/tenancyRow-level tenant isolation via PostgreSQL RLS
@nestarc/safe-responseStandardized API response wrapping + Swagger
@nestarc/audit-logPostgreSQL automatic tracking and PostgreSQL/SQL Server transactional manual events
@nestarc/feature-flagDB-based feature flags with tenant overrides
@nestarc/soft-deletePrisma soft-delete with cascade and restore
@nestarc/paginationCursor + offset pagination with filters
@nestarc/idempotencyIETF draft-07-compatible idempotency with response/header replay
@nestarc/outboxTransactional outbox for reliable domain events
@nestarc/inboxDurable incoming event deduplication with business writes and completion in one transaction
@nestarc/webhookOutbound webhook delivery with signing, retry, and logs
@nestarc/api-keysTenant-scoped machine authentication with scopes, rotation, IP policy, and lifecycle hooks
@nestarc/rbacTenant-aware roles, permissions, and resource-scoped guards
@nestarc/data-subjectGDPR/CCPA export and erase workflows
@nestarc/jobsTenant-aware jobs with in-memory fairness, durable BullMQ retry/dedupe, and first-party outbox publishing

For inbound webhooks or broker consumers, start with Inbox installation. Inbox 0.2.0 requires NestJS ^11.2.8 and Prisma ^7.10.1; authenticate the sender and acknowledge only after durable acceptance. Its processing contract explains how retained message identities protect committed database work independently of an HTTP response-cache TTL.

Tooling ​

@nestarc/mcp-guard is published under the same npm scope, but is separate from the NestJS SaaS module stack. It statically scans MCP servers and client configuration files before you connect them to AI coding tools. See mcp-guard.

Prisma Extension Chaining ​

Use tenancy 0.16.4, audit-log 0.8.0, and soft-delete 0.7.6 for tenant-scoped, audited deletes and restores. This recipe remains on 0.8.0 because soft-delete 0.7.6 does not include audit-log 0.9.0 in its peer range. Upgrade soft-delete 0.7.5 or earlier to 0.7.6 before installing audit-log 0.8.0. This combination supports NestJS 10/11 and requires Node.js ^22.23.4 || ^24.22.1.

Keep the queries in the quick start on the tenancy-extended client. Build a second client from the same base for lifecycle writes, applying audit-log first and soft-delete second. Configure audit-log with consistency: 'atomic-required', tenantRequired: true, and a tenant resolver reading the authorized context. Configure soft-delete with auditLifecycle: 'atomic-required'. The extension chaining guide shows the complete client setup and Nest provider registration.

Inside an authorized request, pass the tenancy callback directly to the lifecycle client's transaction owner:

typescript
import { tenancyTransactionCallback } from '@nestarc/tenancy';
import type { AuditTransactionMethods } from '@nestarc/audit-log';
import type { Prisma } from './generated/prisma/client';

const owner = lifecycleClient as unknown as Pick<
  AuditTransactionMethods<Prisma.TransactionClient>, 'withAuditTransaction'
>;
await owner.withAuditTransaction(tenancyTransactionCallback(
  tenancyService,
  async (tx: Prisma.TransactionClient) => tx.user.delete({ where: { id: userId } }),
));

The callback binds the tenant to the same PostgreSQL transaction that owns the deletion and its audit record. Supply required tenant fields explicitly on inserts and use the callback's tx for model operations. Keep the application's RLS policies and restricted runtime role in place. The release integration test exercises concurrent tenants, restore, permanent deletion, and rollback after an audit insert fails, including when the callback catches that failure.

Last updated:

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