NestJS Domain Whitelisting & Secure Multi-Tenant Backend Filters

The written version
When building multi-tenant SaaS applications in NestJS, trusting the `Host` or `Origin` header blindly will leave your system vulnerable to cache poisoning and tenant data leaks.
The Threat Model
In modern enterprise architectures, enterprise clients demand custom domains (e.g., `portal.clienta.com`) routing to the same NestJS API cluster.
If your middleware doesn't validate whether `clienta.com` is an authorized, verified tenant domain in your database, malicious actors can point their DNS to your cluster and spoof origin context.
Building a Dynamic Domain Interceptor
Here is the production pattern we use in NestJS with Redis caching to validate incoming hostnames in sub-millisecond time without hammering the primary database on every hit.
import { Injectable, NestMiddleware, ForbiddenException } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class TenantDomainMiddleware implements NestMiddleware {
private allowedDomains = new Set([
'api.dipeshsah.com.np',
'localhost:3000',
'admin.dipeshsah.com.np'
]);
use(req: Request, res: Response, next: NextFunction) {
const host = req.headers.host?.split(':')[0];
if (!host || (!this.allowedDomains.has(host) && !this.isVerifiedTenant(host))) {
throw new ForbiddenException('Untrusted domain origin');
}
req['tenantDomain'] = host;
next();
}
private isVerifiedTenant(host: string): boolean {
// In production, check cached tenant whitelist in Redis
return host.endsWith('.dipeshsah.com.np');
}
}Always articulate the trade-offs: don't just say “JWT is faster”. Explain that stateless tokens trade off instantaneous revocation for infinite horizontal read scalability. That separates junior memorize-answers from real systems thinkers.

One email when a post goes up. Nothing else. There is also an RSS feed.