# @dzangolab/fastify-multi-tenant

> Fastify multi-tenant plugin

Latest version **0.79.0** (published 2025-03-11) · MIT license · 0 weekly downloads

## Install

```sh
npm install @dzangolab/fastify-multi-tenant
pnpm add @dzangolab/fastify-multi-tenant
yarn add @dzangolab/fastify-multi-tenant
bun add @dzangolab/fastify-multi-tenant
```

## Health

**Score 55/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high maintenance score; high quality score.

Warnings: low downloads; pre 1.0.

Negative: stale.

## Facts

| | |
|---|---|
| Version | 0.79.0 |
| Published | 2025-03-11 |
| First published | 2023-01-26 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=18 |
| Dependencies | 4 |
| Unpacked size | 272.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 8 |
| Maintainers | opichon, uddhab, rameshlohala, cpxpratik |

## Links

- npm: https://www.npmjs.com/package/@dzangolab/fastify-multi-tenant
- Repository: https://github.com/dzangolab/fastify
- Homepage: https://github.com/dzangolab/fastify/tree/main/packages/multi-tenant#readme
- Issues: https://github.com/dzangolab/fastify/issues
- npm.io page: https://npm.io/package/@dzangolab/fastify-multi-tenant

## Dependencies (4)

- [pg](https://npm.io/package/pg.md) 8.13.1
- [humps](https://npm.io/package/humps.md) 2.0.1
- [lodash.merge](https://npm.io/package/lodash.merge.md) 4.6.2
- [@dzangolab/postgres-migrations](https://npm.io/package/@dzangolab/postgres-migrations.md) 5.4.2

## Recent versions

- 0.79.0 (latest) — 2025-03-11
- 0.78.0 — 2025-03-07
- 0.77.7 — 2025-02-19
- 0.77.6 — 2025-02-19
- 0.77.5 — 2025-02-18
- 0.77.4 — 2025-02-14
- 0.77.3 — 2025-02-03
- 0.77.2 — 2025-01-27
- 0.77.1 — 2025-01-27
- 0.77.0 — 2025-01-03
- 0.76.4 — 2024-12-31
- 0.76.3 — 2024-12-25
- 0.76.2 — 2024-12-24
- 0.76.1 — 2024-12-19
- 0.76.0 — 2024-12-18
- … 136 more at https://npm.io/package/@dzangolab/fastify-multi-tenant/versions

## README

# @dzangolab/fastify-multi-tenant

A [Fastify](https://github.com/fastify/fastify) plugin that adds support for multi-tenant architecture in your API.

## Requirements

* [@dzangolab/fastify-config](../config/)
* [@dzangolab/fastify-mailer](../mailer/)
* [@dzangolab/fastify-slonik](../slonik/)
* [@dzangolab/fastify-user](../user/)

## Tenants table

You need to create a table containing the tenants. You can name the table as you wish. The default name is `tenants`.

The table should contain the following columns:

| Purpose      | Type                              | Constraints               |  Default column name |
|--------------|-----------------------------------|---------------------------|----------------------|
| Identifier   | `integer \| varchar(255) \| uuid` | `PK`                      | `id`                 |
| Display name | varchar(255)                      | `NOT NULL`                | `name`               |
| Owner ID     | varchar(36)                       |                           | `owner_id`           |
| Slug         | varchar(63)                       | `NOT NULL UNIQUE`         | `slug`               |
| Domain       | varchar(255)                      | `UNIQUE`                  | `domain`             |
| created_at   | TIMESTAMP                         | `DEFAULT NOW() NOT NULL`  | `created_at`         |
| updated_at   | TIMESTAMP                         | `DEFAULT NOW() NOT NULL`  | `updated_at`         |

The `owner_id` column serves as a foreign key referencing the `id` column in the `users` table.

## Installation

Install with npm:

```bash
npm install @dzangolab/fastify-config @dzangolab/fastify-mailer @dzangolab/fastify-slonik @dzangolab/fastify-multi-tenant @dzangolab/fastify-user
```
Install with pnpm:

```bash
pnpm add --filter "@scope/project" @dzangolab/fastify-config @dzangolab/fastify-mailer @dzangolab/fastify-slonik @dzangolab/fastify-multi-tenant @dzangolab/fastify-user
```

## Usage

### Register the fastify plugin

Register the plugin with your Fastify instance:

```typescript
import configPlugin from "@dzangolab/fastify-config";
import mailerPlugin from "@dzangolab/fastify-mailer";
import multiTenantPlugin, { tenantMigrationPlugin } from "@dzangolab/fastify-multi-tenant"
import slonikPlugin, { migrationPlugin } from "@dzangolab/fastify-slonik"
import userPlugin from "@dzangolab/fastify-user";
import Fastify from "fastify";

import config from "./config";

import type { ApiConfig } from "@dzangolab/fastify-config";
import type { FastifyInstance } from "fastify";

const start = async () => {
  // Create fastify instance
  const fastify = Fastify({
    logger: config.logger,
  });
  
  // Register fastify-config plugin
  await fastify.register(configPlugin, { config });

  // Register mailer plugin
  await fastify.register(mailerPlugin, config.mailer);
  
  // Register database plugin
  await fastify.register(slonikPlugin, config.slonik);
  
  // Register multi tenant plugin
  await fastify.register(multiTenantPlugin);
  
  // Register user plugin
  await fastify.register(userPlugin);
  
  // Run app database migrations
  await fastify.register(migrationPlugin, config.slonik);
  
  // Run tenant database migrations
  await fastify.register(tenantMigrationPlugin);

  await fastify.listen({
    port: config.port,
    host: "0.0.0.0",
  });
};

start();
```

## Configuration

If you are not using the default table name and columns, add the following configuration to your `config`:

```typescript
const config: ApiConfig = {
  // ...
  multiTenant: {
    reserved: {
      slugs: ["..."],
      domains: ["..."],
    },
    rootDomain: "";
    table: {
      columns: {
        id: "...",
        domain: "...",
        name: "...",
        ownerId: "...",
        slug: "...",
      },
      name: "...",
    },
  }
};
```
## Using GraphQL

This package supports integration with [@dzangolab/fastify-graphql](../graphql/).

### Configuration

Add the required context for the fastify-user package by including `multiTenantPlugin` in your GraphQL configuration as shown below:

```typescript
import multiTenantPlugin from "@dzangolab/fastify-multi-tenant";
import userPlugin from "@dzangolab/fastify-user";
import type { ApiConfig } from "@dzangolab/fastify-config";

const config: ApiConfig = {
  // ...other configurations...
  graphql: {
    // ...other graphql configurations...
    plugins: [userPlugin, multiTenantPlugin],
  },
  // ...other configurations...
};
```

### Schema Integration
This package does not provide a predefined schema. To integrate it into your GraphQL setup, add the following to your GraphQL schema:

```graphql
type Tenant {
  id: Int!
  name: String
  slug: String!
  domain: String
  ownerId: String
  createdAt: Float!
  updatedAt: Float!
}

type Tenants {
  totalCount: Int
  filteredCount: Int
  data: [Tenant]!
}

input TenantCreateInput {
  name: String
  slug: String!
  domain: String
}

type Mutation {
  createTenant(data: TenantCreateInput): Tenant @auth
}

type Query {
  allTenants(fields: [String]): [Tenant]! @auth
  tenant(id: Int): Tenant @auth
  tenants(limit: Int, offset: Int, filters: Filters, sort: [SortInput]): Tenants! @auth
}
```

### Resolver Integration

To integrate the resolvers provided by this package, import them and merge with your application's resolvers:

```typescript
import { tenantResolver } from "@dzangolab/fastify-multi-tenant";

import type { IResolvers } from "mercurius";

const resolvers: IResolvers = {
  Mutation: {
    // ...other mutations ...
    ...tenantResolver.Mutation,
  },
  Query: {
    // ...other queries ...
    ...tenantResolver.Query,
  },
};

export default resolvers;
```

---
_Source: https://npm.io/package/@dzangolab/fastify-multi-tenant · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
