QA
Intermediate LevelExpress JS

How do you host multiple domain names or subdomains within a single Express server instance using vhost?

❓ Interview Prompt: Explain multi-domain hosting, vhost middleware, routing by Host header, and mounting domain-specific Express apps.

The 'vhost' middleware inspects incoming HTTP 'Host' request headers and routes requests to different Express sub-applications based on the requested domain or subdomain.

Usage:

Host multiple distinct domain names (e.g., 'admin.company.com' vs 'api.company.com') within a single running Express server instance.

Code Implementation Example

javascript
import express from 'express';
import vhost from 'vhost';

const apiApp = express();
apiApp.get('/', (req, res) => res.send('API Domain Host'));

const adminApp = express();
adminApp.get('/', (req, res) => res.send('Admin Domain Host'));

const mainApp = express();
mainApp.use(vhost('api.company.com', apiApp));
mainApp.use(vhost('admin.company.com', adminApp));

mainApp.listen(80);
💡Multi-domain virtual hosting using vhost middleware.
🎯 Interview Key Takeaway

Use vhost middleware to route incoming requests to different sub-apps based on the client Host domain header.

#vhost#Subdomains#Multi-Tenant#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?