npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nestjs-tenancy

v1.0.9

Published

Nestjs module for multitenancy support in Sequilize

Readme

nestjs-tenancy

A simple easy to use multitenancy module for NestJs and Sequelize

Description

Multitenancy Module for Nest using Sequelize or Sequelize TypeScript.

Installation

$ npm i --save nestjs-tenancy

Basic usage

app.module.ts

import { Module } from "@nestjs/common";

import { TenancyModule } from "nestjs-tenancy";

import { UserModule } from "./user.module.ts";

@Module({
  imports: [
    TenancyModule.forRoot({
      tenantIdentifier: 'X-TENANT',
      uri: (tenant: string) => 
        `postgresql://postgresql:@127.0.0.1:5432/${tenant}?schema=public`,
    }),
    UserModule,
  ],
})
export class AppModule {}

Create your Sequelize model

user.model.ts

import { 
  Table, 
  Model, 
  Column, 
  PrimaryKey 
} from 'sequelize-typescript';

@Table()
export class User extends Model {
    @Column()
    name: string;

    @Column()
    email: number;

    @Column()
    password: string;
}

Inject User for UserModule

user.module.ts

import { Module } from '@nestjs/common';
import { TenancyModule } from 'nestjs-tenancy';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { User } from './user.model';

@Module({
  imports: [
    TenancyModule.forFeature([User])
  ],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule { }

Get the User model in a service

user.service.ts

import { Injectable } from '@nestjs/common';
import { InjectTenancyModel } from 'nestjs-tenancy';
import { User } from './user.model';

@Injectable()
export class UserService {
  constructor(
    @InjectTenancyModel(User.name) 
    private readonly user: typeof User
  ) { }

  async create(user: Partial<User>): Promise<User> {
    return this.user.create(user);
  }

  async findAll(): Promise<User[]> {
    return this.user.findAll<User>();
  }
}

Finally, use the service in a controller!

user.controller.ts


import { Body, Controller, Get, Post } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.model';

@Controller('user')
export class UserController {
  constructor(private readonly user: UserService) { }

  @Post()
  async create(@Body() user: Partial<User>) {
    return this.user.create(user);
  }

  @Get()
  async findAll(): Promise<User[]> {
    return this.user.findAll();
  }
}

Adding custom validators for the tenant

Let's say you want to handle a validation check to see if your tenant is registered. You can do this by implementing the TenancyValidator interface and writing your own validation logic inside the validate method. The library invokes this method internally.

Note

Here we assume that X-TENANT is passed in the request header so that its available for the validator.

custom-tenant.validator.ts

import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectModel } from '@nestjs/sequelize';

import { TenancyValidator } from "nestjs-tenancy";

import { Tenant } from './tenant.model';

@Injectable()
export class CustomTenantValidator implements TenancyValidator {
    private _tenantId: string;

    // This`Tenant` model definition schema is mapped to the common database and
    // not into the tenant database.
    constructor(@InjectModel(Tenant) private tenant: typeof Tenant) { }

    /**
     * Method to set the tenant id
     *
     * @param {string} tenantId
     * @returns
     * @memberof CustomTenantValidator
     */
    setTenantId(tenantId: string): TenancyValidator {
        this._tenantId = tenantId;
        return this; // Make sure to return the instance of the class back here.
    }

    /**
     * Your Custom Validation to verify if tenant exist in the common database
     *
     * Note: This method will be invoked by the library internally when
     * tenant id is present in the context.
     *
     * @returns {Promise<void>}
     * @memberof CustomTenantValidator
     */
    async validate(): Promise<void> {
        const exist = await this.tenant.exists({ name: this._tenantId });
        if (!exist) {
            throw new NotFoundException(`Tenant not found`);
        }
    }
}

Export the validator from your tenant module

tenant.module.ts

import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';

import { Tenant } from './tenant.model';
import { CustomTenantValidator } from './custom-tenant.validator';
import { TenantController } from './tenant.controller';
import { TenantService } from './tenant.service';

@Module({
  imports: [
    // Here the connection represents the common database
    SequelizeModule.forFeature([Tenant])
  ],
  controllers: [TenantController],
  providers: [
    TenantService,
    // Your custom validator
    CustomTenantValidator,
  ],
  exports: [
    TenantService,
    CustomTenantValidator,
  ]
})
export class TenantModule {}

Finally you will also need to modify the module configuration.

app.module.ts

import { Module } from "@nestjs/common";

import { TenancyModule } from "nestjs-tenancy";

import { UserModule } from "./user.module";
import { TenantModule } from './tenant/tenant.module';

@Module({
  imports: [
    TenancyModule.forRootAsync({
      imports: [TenantModule]
      useFactory: async (validator: CustomTenantValidator) => {
        return {
          tenantIdentifier: 'X-TENANT',
          uri: (tenantId: string) => 
            `postgresql://postgresql:@127.0.0.1:5432/${tenantId}?schema=public`,
          validator: (tenantId: string) => validator.setTenantId(tenantId)
        };
      },
      inject: [CustomTenantValidator]
    }),
    UserModule,
  ],
})
export class AppModule {}

Subdomain support

This library also enables the extraction of tenant id from the sudomain of the url. For enabling this you need to modify your configuration like below.

app.module.ts

import { Module } from "@nestjs/common";

import { TenancyModule } from "nestjs-tenancy";

import { UserModule } from "./user.module.ts";

@Module({
  imports: [
    TenancyModule.forRoot({
      isTenantFromSubdomain: true,
      uri: (tenant: string) => 
        `postgresql://postgresql:@127.0.0.1:5432/${tenant}?schema=public`,
    }),
    UserModule,
  ],
})
export class AppModule {}

Requirements

  1. sequelize ^6.6.5
  2. sequelize-typescript ^2.1.0

Test

# e2e tests
$ npm run test:e2e

License

Nest is MIT licensed.

Credits

This is forked from @needle-innovision/nestjs-tenancy which is built for Mongoose do checkout if you need Multi Tenancy for your Mongoose based NestJs App.