Real World Example

Multi-tenant SaaS Middleware

B2B SaaS products like Zoho, Freshworks or a white-label ShopEase serve many companies (tenants) from one API. A middleware reads the tenant from the subdomain and attaches it to the request for every later layer.

src/tenancy/tenant.middleware.ts

import { Injectable, NestMiddleware, NotFoundException } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express';
import { TenantsService } from './tenants.service';

declare module 'express' {
  interface Request { tenant?: { id: string; plan: 'free' | 'pro' } }
}

@Injectable()
export class TenantMiddleware implements NestMiddleware {
  constructor(private readonly tenants: TenantsService) {}

  async use(req: Request, _res: Response, next: NextFunction) {
    const sub = req.hostname.split('.')[0];            // acme.shopease.in -> acme
    const tenant = await this.tenants.findBySubdomain(sub);
    if (!tenant) throw new NotFoundException(`Unknown store "${sub}"`);
    req.tenant = { id: tenant.id, plan: tenant.plan };
    next();
  }
}

Example

curl -s https://acme.shopease.in/api/products | head -c 80
curl -s https://nosuch.shopease.in/api/products

Example output

{"data":[{"id":1,"name":"Acme Cotton Kurta","price":899},{"id":2,"name":
{"message":"Unknown store \"nosuch\"","error":"Not Found","statusCode":404}