미들웨어와 AsyncLocalStorage를 통한 테넌트 확인
AsyncLocalStorage 컨텍스트를 사용해 요청에서 현재 테넌트를 추출하고 전파합니다.
미들웨어와 AsyncLocalStorage를 통한 테넌트 확인은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Multi-Tenancy Problem
In a multi-tenant backend, one running instance serves many customers (tenants). Every request belongs to exactly one tenant, and almost every layer needs to know which one: the database connection, query filters, caches, audit logs, even outbound emails.
- Passing a
tenantIdargument down through every service method is noisy and error-prone. - Forget it once in a query and you leak tenant A's data to tenant B — a critical security bug.
We need to resolve the tenant once at the edge of the request and propagate it implicitly to everything that runs during that request.
Where Does the Tenant Come From?
Resolution strategy depends on your routing model. Common sources, in order of how early they are available:
- Subdomain:
acme.api.example.com→ tenantacme. - Header:
X-Tenant-Id: acme(common for internal/service-to-service calls). - JWT claim: a
tidclaim inside the access token. - Path prefix:
/t/acme/orders.
Whatever the source, the goal is to turn raw request data into a validated tenant identifier as early as possible — ideally in middleware, which runs before guards, interceptors, and controllers.
function resolveTenantFromHost(host: string): string | null {
// acme.api.example.com -> "acme"
const parts = host.split('.');
if (parts.length < 3) return null;
const sub = parts[0];
return /^[a-z0-9-]+$/.test(sub) ? sub : null;
}
console.log(resolveTenantFromHost('acme.api.example.com')); // acme
console.log(resolveTenantFromHost('localhost')); // null
console.log(resolveTenantFromHost('BAD!.api.example.com')); // nullWhy Not Just Use the Request Object?
A naive approach is to attach the tenant to req and read req.tenantId everywhere. This works in controllers and guards but breaks down quickly:
- Deep services would need the
Requestinjected (@Inject(REQUEST)), forcing them to be request-scoped, which is contagious and hurts performance. - Code with no access to
req— a repository helper, a logger formatter, a TypeORM subscriber — has no clean way to read it.
We want a way to ask "what tenant am I serving right now?" from anywhere in the async call stack, without threading req through. That is exactly what AsyncLocalStorage provides.
AsyncLocalStorage in 60 Seconds
AsyncLocalStorage (from Node's built-in async_hooks) gives you a per-request store that survives across await boundaries, timers, and callbacks. You call als.run(store, callback) once, and any code executed inside that callback — however deep, however async — can call als.getStore() to read the same store.
It is conceptually thread-local storage for Node's single-threaded async model. Each request gets its own isolated store; concurrent requests never see each other's data.
import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage<{ tenantId: string }>();
async function deepWork(): Promise<void> {
await new Promise((r) => setTimeout(r, 10));
const store = als.getStore();
console.log('deep sees:', store?.tenantId);
}
async function handle(tenantId: string): Promise<void> {
await als.run({ tenantId }, async () => {
await deepWork();
});
}
// Two concurrent "requests" stay isolated
Promise.all([handle('acme'), handle('globex')]);Designing the Tenant Context Store
Wrap AsyncLocalStorage in a small, typed service so the rest of the app never touches Node internals directly. Keep the store shape minimal but extensible — at least the tenant id, plus anything else you want request-scoped (request id, user id).
run(store, cb)— enter a new context for one request.get()— read the current tenant, throwing if called outside any context (fail loud, not silently global).
Making get() throw on a missing context is deliberate: a silent undefined tenant is how cross-tenant leaks happen.
import { AsyncLocalStorage } from 'node:async_hooks';
import { Injectable } from '@nestjs/common';
export interface TenantStore {
tenantId: string;
requestId: string;
}
@Injectable()
export class TenantContext {
private readonly als = new AsyncLocalStorage<TenantStore>();
run<T>(store: TenantStore, cb: () => T): T {
return this.als.run(store, cb);
}
get(): TenantStore {
const store = this.als.getStore();
if (!store) {
throw new Error('TenantContext accessed outside of a request scope');
}
return store;
}
get tenantId(): string {
return this.get().tenantId;
}
}The Tenant Resolution Middleware
Middleware is the right place to resolve and open the context because it runs at the very start of the request, before guards and route handlers. The middleware:
- Extracts the raw tenant hint (header, subdomain, etc.).
- Validates it and rejects unknown tenants with
400/404. - Calls
tenantContext.run(...)and invokesnext()inside the callback so the entire downstream pipeline executes within the context.
The critical detail: next() must be called inside run(). If you call next() after run() returns, the context is already closed and every getStore() downstream returns undefined.
import { Injectable, NestMiddleware, BadRequestException } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { randomUUID } from 'node:crypto';
import { TenantContext } from './tenant.context';
@Injectable()
export class TenantMiddleware implements NestMiddleware {
constructor(private readonly tenantContext: TenantContext) {}
use(req: Request, res: Response, next: NextFunction): void {
const tenantId = req.header('x-tenant-id');
if (!tenantId || !/^[a-z0-9-]+$/.test(tenantId)) {
throw new BadRequestException('Missing or invalid X-Tenant-Id');
}
const store = { tenantId, requestId: randomUUID() };
// next() MUST run inside the context callback
this.tenantContext.run(store, () => next());
}
}Wiring the Middleware Globally
Register the middleware in a module's configure method and apply it to all routes. Because TenantContext is injected into the middleware, both must be provided/exported from a module the app imports.
Order matters: the tenant middleware should run before anything that depends on the context (logging middleware, etc.). NestJS applies middleware in the order you chain .apply() calls and in module import order.
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { TenantContext } from './tenant.context';
import { TenantMiddleware } from './tenant.middleware';
@Module({
providers: [TenantContext],
exports: [TenantContext],
})
export class TenantModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(TenantMiddleware).forRoutes('*');
}
}Consuming the Tenant Anywhere
Now any provider — at any depth, request-scoped or not — can inject TenantContext and read the current tenant. No @Inject(REQUEST), no request-scoped contagion, no passing tenantId through method signatures.
This is the payoff: a singleton service can safely ask for the current tenant because getStore() resolves to the right per-request store at call time.
import { Injectable } from '@nestjs/common';
import { TenantContext } from './tenant.context';
@Injectable()
export class OrderService {
constructor(private readonly tenantContext: TenantContext) {}
async listOrders() {
const { tenantId } = this.tenantContext.get();
// Every query is automatically scoped to the active tenant
return this.repo.find({ where: { tenantId } });
}
// injected elsewhere
private repo: any;
}Scoping the Database Automatically
The biggest win is enforcing tenant isolation at the data layer instead of trusting every developer to add where tenantId = .... With the context available globally, you can centralize it:
- Connection-per-tenant: resolve a tenant-specific datasource/connection from a pool using
tenantContext.tenantId. - Shared schema + filter: a TypeORM/Prisma global filter or query subscriber that injects the tenant predicate.
Both approaches read the tenant from AsyncLocalStorage, so the resolver logic lives in exactly one place.
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TenantContext } from './tenant.context';
@Injectable()
export class TenantConnectionProvider {
private readonly pool = new Map<string, DataSource>();
constructor(private readonly tenantContext: TenantContext) {}
getDataSource(): DataSource {
const tenantId = this.tenantContext.tenantId;
const ds = this.pool.get(tenantId);
if (!ds) {
throw new Error(`No datasource initialized for tenant ${tenantId}`);
}
return ds;
}
}Middleware vs Guards vs Interceptors
Why middleware and not a guard or interceptor for opening the context?
- Middleware runs first and wraps the entire remaining pipeline inside its
next()callback — guards, interceptors, pipes, and the handler all execute withinrun(). This is what we want. - Guards/interceptors run later. An interceptor wraps the handler but not the guards that ran before it, so context opened there is partially missing.
One nuance: if you must resolve the tenant from a verified JWT, the token is validated in a guard, which runs after middleware. A common pattern is middleware to open the store and a guard/early step to populate the tenant once the JWT is verified.
Pitfalls That Break Context Propagation
AsyncLocalStorage is robust across async/await and setTimeout, but a few things silently drop the context:
- Detached work: tasks pushed to a queue or run after the response (fire-and-forget jobs, cron triggered work) run outside the request and have no store. Capture
tenantIdexplicitly before handing off. - Some pools/native callbacks that use non-promise scheduling can lose context — verify, and re-bind with
als.runif needed. - Calling
get()in app bootstrap or in a health check that bypasses the middleware throws — guard such paths or skip the middleware for them.
Rule of thumb: anything that outlives the HTTP request must be given the tenant explicitly, not via the store.
import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage<{ tenantId: string }>();
const queue: Array<() => void> = [];
function enqueueJob(work: () => void): void {
// WRONG: read store now? It's fine here, but the job runs later/outside.
const tenantId = als.getStore()?.tenantId; // capture explicitly
queue.push(() => als.run({ tenantId: tenantId! }, work));
}
als.run({ tenantId: 'acme' }, () => {
enqueueJob(() => console.log('job tenant:', als.getStore()?.tenantId));
});
// Drain later, outside the original context
queue.forEach((job) => job()); // job tenant: acmeQuick Check
You implement tenant resolution in a NestJS middleware that calls tenantContext.run(store, ...). Deep services using a singleton (default-scoped) provider read the tenant via getStore().
Recap
You built implicit, leak-resistant tenant propagation:
- Resolve early: middleware extracts and validates the tenant from header/subdomain/JWT at the request edge.
- Propagate implicitly: wrap
AsyncLocalStoragein a typedTenantContextservice; callrun(store, () => next())so the whole pipeline executes inside the context. - Consume anywhere: any singleton provider injects
TenantContextand reads the tenant — no request-scoped contagion, no threadingtenantIdthrough signatures. - Enforce isolation centrally at the data layer (connection-per-tenant or a global query filter).
- Mind the boundaries: detached/queued/scheduled work loses the store — capture
tenantIdexplicitly, and makeget()throw outside a request to fail loud.
자주 묻는 질문
“미들웨어와 AsyncLocalStorage를 통한 테넌트 확인” 강의는 무료인가요?
네 — “미들웨어와 AsyncLocalStorage를 통한 테넌트 확인” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“미들웨어와 AsyncLocalStorage를 통한 테넌트 확인”에서 뭘 배우나요?
AsyncLocalStorage 컨텍스트를 사용해 요청에서 현재 테넌트를 추출하고 전파합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“미들웨어와 AsyncLocalStorage를 통한 테넌트 확인” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 미들웨어와 AsyncLocalStorage를 통한 테넌트 확인
- 테넌트별 스키마 데이터베이스 연결
- 구성 가능한 동적 모듈 구축
- 요청 범위 공급자와 그 트레이드오프