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 🙏

© 2025 – Pkg Stats / Ryan Hefner

express-multitenancy

v0.0.5

Published

Express middleware for managing multi-tenant applications with configurable tenant resolution strategies

Readme

Express Multitenancy

A flexible and powerful solution for implementing multi-tenancy in Express applications with MongoDB/Mongoose support.

Features

  • Multiple tenant identification strategies
    • Header-based tenant identification (included)
    • Easily extend with your own custom strategies
  • Flexible tenant storage options
    • In-memory storage for development/testing
    • MongoDB storage for production use
    • Support for custom storage implementations
  • Mongoose integration
    • Automatic tenant filtering for all queries
    • Transparent tenant ID assignment for new documents
    • Support for exempt models (global resources)
  • TypeScript support
    • Full TypeScript type definitions
    • Generic support for custom tenant types

Installation

npm install express-multitenancy

Quick Start

const express = require('express');
const mongoose = require('mongoose');
const { multitenancy, HeaderStrategy, MongooseStore } = require('express-multitenancy');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/multitenancy');

// Create a tenant store
const mongooseStore = new MongooseStore({
  connection: mongoose.connection
});

// Add sample tenants
(async () => {
  await mongooseStore.add({ id: 'tenant1', name: 'Tenant 1' });
  await mongooseStore.add({ id: 'tenant2', name: 'Tenant 2' });
})();

// Apply multitenancy middleware
app.use(multitenancy({
  strategies: [new HeaderStrategy('x-tenant-id')],
  store: mongooseStore,
}));

// Use tenant in routes
app.get('/', (req, res) => {
  res.send(`Hello, ${req.tenant?.name || 'Unknown Tenant'}!`);
});

app.listen(3000);

API Reference

Tenant Identification Strategies

HeaderStrategy

Identifies tenants based on an HTTP header.

const { HeaderStrategy } = require('express-multitenancy');

// Create a strategy that looks for tenant ID in x-tenant-id header
const headerStrategy = new HeaderStrategy('x-tenant-id');

RouteStrategy

Identifies tenants based on route parameters.

const { RouteStrategy } = require('express-multitenancy');

// Create a strategy that extracts tenant ID from 'tenantId' route parameter
const routeStrategy = new RouteStrategy(); 

// For Express 5 compatibility, mount the middleware on specific routes
app.use(['/api/:tenantId', '/api/:tenantId/*'], multitenancy({
  strategies: [routeStrategy],
  store: myStore
}));

// Or with a custom parameter name
const customRouteStrategy = new RouteStrategy('organizationId');
app.use(['/api/:organizationId', '/api/:organizationId/*'], multitenancy({
  strategies: [customRouteStrategy],
  store: myStore
}));

Tenant Storage Providers

InMemoryStore

Stores tenants in memory. Useful for development or applications with a small fixed set of tenants.

const { InMemoryStore } = require('express-multitenancy');

const store = new InMemoryStore([
  { id: 'tenant1', name: 'Tenant One' },
  { id: 'tenant2', name: 'Tenant Two' }
]);

MongooseStore

Stores tenants in MongoDB using Mongoose. Suitable for production applications.

const { MongooseStore } = require('express-multitenancy');

// Basic usage with default schema
const store = new MongooseStore({
  connection: mongoose.connection,
  // Optional: custom model name (default: 'Tenant')
  modelName: 'Organization'
});

// Using a custom model
const store = new MongooseStore({
  connection: mongoose.connection,
  model: CustomTenantModel
});

Mongoose Integration

multitenancyPlugin

Plugin that adds tenant filtering to Mongoose schemas.

const { multitenancyPlugin } = require('express-multitenancy');

// Apply to specific schema
const userSchema = new mongoose.Schema({...});
userSchema.plugin(multitenancyPlugin);

// OR: Apply globally to all schemas
mongoose.plugin(multitenancyPlugin);

Custom Tenant Types

You can extend the base Tenant interface to add custom properties:

import { Tenant, InMemoryStore } from 'express-multitenancy';

// Custom tenant type
interface OrganizationTenant extends Tenant {
  domain: string;
  plan: 'free' | 'premium' | 'enterprise';
  createdAt: Date;
}

// Use with generic type parameter
const store = new InMemoryStore<OrganizationTenant>([
  {
    id: 'org1',
    name: 'Acme, Inc.',
    domain: 'acme.com',
    plan: 'enterprise',
    createdAt: new Date()
  }
]);

License

ISC