Express.js Middleware for Multi-Tenant Routing
Below is a simplified example of Express.js middleware for routing requests to the appropriate tenant-specific database collection:
// Express middleware for multi-tenant routing
function multiTenantMiddleware(req, res, next) {
const tenantId = req.user.tenantId; // Extract tenant ID from authenticated user
const db = /* MongoDB connection */;
// Dynamically select collection based on tenant ID
const collection = db.collection(`tenant_${tenantId}`);
// Attach collection to request object for downstream processing
req.collection = collection;
next();
}
// Example usage in Express route
app.get('/contacts', multiTenantMiddleware, (req, res) => {
// Use the attached collection to find all contacts for the current tenant
req.collection.find({}).toArray((err, data) => {
if (err) {
return res.status(500).json({ error: 'Internal Server Error' });
}
res.json(data);
});
});
Explanation:
- The
multiTenantMiddleware
function is used as middleware in an Express route to handle multi-tenant routing. It extracts thetenantId
from the authenticated user’s request and dynamically selects the collection based on thetenantId
. - In the example usage, the middleware is applied to the
/contacts
route. It uses the attachedcollection
to find all contacts for the current tenant and returns them as a JSON response. If there is an error, it returns a 500 status code with an error message.
Build a Multi-Tenant Architecture in MongoDB
In the dynamic landscape of modern software development, accommodating multiple tenants within a single application is becoming increasingly common. Whether weu’re building a SaaS (Software as a Service) platform or a multi–user application also adopting a multi-tenant architecture is essential for scalability, efficiency and cost–effectiveness.
In this comprehensive guide, we’ll explore How to build a multi-tenant architecture in MongoDB, a popular NoSQL database, through clear explanations and practical examples.