how --host flag works in vite (internally)
Rishab Raj
Published on
Intro
Oftentimes we create applications or websites and we want to test that creation on multiple devices and if that application is created using vite then it provides us with a cli flag which makes our lives easier as developer
Theory
Before we get into the technical stuff we have to get familiar with 2 IP addresses :
- localhost or 127.0.0.1 - some people call it loopback address and whenever we host our application on this port that application is only accessible from the same device it is the default address we use while developing our applications.
Difference between localhost and 127.0.0.1
It is not necessary for localhost to be equal to 127.0.0.1 as in IPv4 address reserves 127.0.0.1 to 127.255.255.255 to loopback address hence in normal cases it will be equal but could be unequal if localhost is configured so some other address or in IPv6 only systems. Also when we use 127.0.0.1 our request is routed through network card but that is not the case when using 'localhost'
- 0.0.0.0 - this address is a special address, whenever we host our application on this address with a port number then any request to our device using public IP address on that specific port number can make our application accessible.
Techincal Stuff
So as we all know vite uses nodejs as web server and node has a special module called http module which is used to create the server. This server has a special method called listen which take port, host(ip address) and a callback function as arguments so lets create a simple web server
import * as http from "node:http"
const server = http.createServer();
server.listen(80,'localhost',(req,res) => {
res.writeHead(200);
res.end("Hello bhai");
});
now if we don’t provide any host address to this function this will create a server on address 0.0.0.0 hence making it available for all of the devices on our network
import * as http from "node:http"
const server = http.createServer();
// server.listen(port,host,calback);
server.listen(80,undefined,(req,res) => {
res.writeHead(200);
res.end("Hello bhai");
});
So what vite does is that when we run pnpm run dev it host our application on localhost (remember loopback) meaning it is accessible only from same device. but when we use —host flag then vite passes undefined in place of host and http module hosts our app on 0.0.0.0 hence making our application available to every device making our lives easier and even localhost:80 also works!