How to host multiple Node.js sites on the same IP or server with different domains?

Sometimes, we want to host multiple Node.js sites on the same IP or server with different domains.

In this article, we’ll look at how to host multiple Node.js sites on the same IP or server with different domains.

How to host multiple Node.js sites on the same IP or server with different domains?

To host multiple Node.js sites on the same IP or server with different domains, we can use the diet package.

To install it, we run

npm i diet

Then we write

const server = require('diet');

const app = server()
app.listen('http://example.com/')
app.get('/', ($) => {
  $.end('hello world ')
})

const sub = server()
sub.listen('http://subdomain.example.com/')
sub.get('/', ($) => {
  $.end('sub domain!')
})

const other = server()
other.listen('http://other.com/')
other.get('/', ($) => {
  $.end('other domain')
})

to call server to create a web server.

And we call listen with the domain of each web server.

Finally, we call get to create a get route with path / on each server.

In the callback of get, we call $.end to send a response.

Conclusion

To host multiple Node.js sites on the same IP or server with different domains, we can use the diet package.