Using Custom Domains with Multiple Localhost Ports for Applications
In the world of web development, running multiple applications on a single machine with different localhost ports is a common scenario.
However, dealing with different localhost ports can often become tedious and difficult to remember. Using custom domains with your localhost is an excellent way to get around this. This approach provides a more user-friendly and intuitive development experience.
Benefits of Using Custom Domains for Localhost Development
Some of the benefits of using custom domains for localhost development include:
- Easier to remember than localhost ports
- Simulates a production-like environment
- Makes switching between applications seamless
Setting Up Custom Domains for Localhost Development
To set up custom domains for localhost development, we need to make entries in our local machine's hosts file. This file maps hostnames to IP addresses. By modifying this file, we can make our custom domain name point to localhost.
For Windows:
C:\Windows\System32\drivers\etc\hosts
For macOS and Linux:
/etc/hosts
By adding the following lines to the hosts file, the domain app.localdev will point to localhost. Replace 8080 with the desired port number.
127.0.0.1 app.localdev
Running Applications on Specific Domains
To run applications on specific domains, you need to use different start-up commands for each application. Here is an example in Node.js and Next.js.
Example in Node.js:
const http = require('http');
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World
');
}).listen(3000, 'app-node.localdev');
console.log(`Server running at http://app-node.localdev:${3000}/`);
Example in Next.js:
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/a') {
app.render(req, res, '/a', query);
} else if (pathname === '/b') {
app.render(req, res, '/b', query);
} else {
handle(req, res, parsedUrl);
}
}).listen(3001, 'app-next.localdev');
console.log(`> Ready on http://app-next.localdev:${3001}`);
});
In conclusion, using custom domains for localhost development can greatly enhance and simplify your web development experience, especially when working with multiple applications running on different ports.