How to setup domains and subdomains in localhost

abdxzi

Abdul Azeez V

Posted on October 15, 2024

How to setup domains and subdomains in localhost

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)
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Install and import required packages

yarn init
yarn add express vhost http-proxy-middleware
Enter fullscreen mode Exit fullscreen mode
const express = require('express');
const vhost = require('vhost');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode
// 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');
});

Enter fullscreen mode Exit fullscreen mode

Now the NextJs frontend will be accessible on address example.local and chat app will be at chat.example.local

Huraay ๐Ÿ˜๐Ÿ˜

Complete Code

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
abdxzi
Abdul Azeez V

Posted on October 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About