In this lesson, you will learn how to enforce data isolation by automatically scoping your database queries to a specific organization or "tenant" using the request pipeline.
The Concept of Tenant Isolation
In a multi-tenant system, a single instance of your Node.js application serves multiple customers (tenants). The greatest risk is a "data leak," where one customer accidentally sees another’s data. To prevent this, we must ensure that every time a request enters our system, we identify who owns the data and strictly filter every database operation by that tenantId.
Implementing the Request Pipeline
Instead of manually adding WHERE tenant_id = ? to every single query, we use middleware to identify the tenant early in the request lifecycle. By combining this with Scoped Dependency Resolution, we can inject the tenantId into our Repository Pattern implementations automatically.
Consider this middleware pattern:
// Middleware to identify the tenant
function identifyTenant(req, res, next) {
const tenantId = req.headers['x-tenant-id'];
if (!tenantId) return res.status(400).send('Tenant missing');
// Store in request context for later retrieval
req.tenantId = tenantId;
next();
}
// Inside your Repository Layer
async function getOrders(req) {
// The repository automatically uses the scoped tenantId
return await db.orders.findMany({
where: { tenantId: req.tenantId }
});
}
Why This Matters
By embedding this logic into your Service Layer Abstraction, you create a "safety net." If a developer forgets to filter by tenantId in a new controller, the repository level can be configured to throw an error or default to the tenantId stored in the Request Context Propagation. This centralized approach ensures that data access is segmented before the application ever attempts to fetch information from your storage layer, maintaining total isolation between your users.
Key Takeaway: Always enforce tenant isolation at the repository level by anchoring every database query to a verified tenant ID extracted from the initial request headers.