Intermediate LevelExpress JS
How do you implement dynamic multi-tenant subdomain routing (tenant1.myapp.com) in Express?
❓ Interview Prompt: Explain req.subdomains, dynamic multi-tenant routing, wildcard DNS, and tenant context isolation.
Multi-tenant SaaS platforms often assign unique subdomains to tenants ('tenant1.myapp.com').
'req.subdomains':
Express parses subdomains into an array: 'req.subdomains' (reverse order).
•
URL: 'tenant1.admin.myapp.com' $\rightarrow$ 'req.subdomains = ["admin", "tenant1"]'.
•
Use middleware to extract the tenant slug, fetch tenant settings from database, and attach 'req.tenant' to the request!
Code Implementation Example
javascript
import express from 'express';
const app = express();
app.use((req, res, next) => {
const tenantSlug = req.subdomains[0]; // Extract primary subdomain
if (!tenantSlug) return next();
// Attach tenant context to request
req.tenant = { slug: tenantSlug, name: `Tenant ${tenantSlug}` };
next();
});
app.get('/', (req, res) => {
res.json({ tenant: req.tenant || 'Main Platform' });
});💡Extracting dynamic subdomains using req.subdomains for multi-tenant routing.
🎯 Interview Key Takeaway
Use req.subdomains to extract client subdomains dynamically and isolate multi-tenant database contexts.
#req.subdomains#Multi-Tenant#Routing#Intermediate
Back to all Express JS Questions→