I was developing a web app having multiple independent apps that meant to be run at different subdomains. So i wanted to mock this domain system in localhost.
Setup
For demo let assume, we have two apps running on ports 3000
(a NextJs Frontend) and 5000
(a ChatApp).
We need to add the all dns mapping to /etc/hosts
file.
sudo nano /etc/hosts # linux, macos
notepad C:\\Windows\\System32\\drivers\\etc\\hosts # windows (Run cmd as Administrator)
Add the domains we need to the end of file. for example:
127.0.0.1 example.local
127.0.0.1 chat.example.local
Install and import required packages
yarn init
yarn add express vhost http-proxy-middleware
const express = require('express');
const vhost = require('vhost');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
Create proxies for apps running on a NextApp running on port 3000
const nextAppProxy = createProxyMiddleware({
target: 'http://localhost:3000',
changeOrigin: true,
ws: true, // Add ws support
logLevel: 'debug', // Add logging for debugging
});
Create proxy for app running on port 5000
const chatAppProxy = createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
ws: true, // Add ws support
logLevel: 'debug' // Add logging for debugging
});
// Set up virtual hosts
app.use(vhost('example.local', nextAppProxy));
app.use(vhost('chat.example.local', chatAppProxy));
app.listen(80, () => {
console.log('Vhost proxy server running on port 80');
});
Now the NextJs frontend will be accessible on address example.local
and chat app will be at chat.example.local
Huraay 😍😍
Top comments (0)