Expose local Vite instance to the network
When you have configured your web application development build using Vite, you might have set it up in your package.json
like so.
{
"scripts": {
"dev": "vite"
}
}
Now, when you spin this dev instance up by running the npm run dev
, here’s what the output might look like.
As you can tell, the command will trigger a local instance at http://localhost:3000/.
Notice that, it also shows the following message.
Network: use
--host
to expose
What’s that? Vite gives a convenient way to expose the local instance to the local network in scenarios where you would want to test your web application, let’s say, on your mobile device.
You may also like → Built-in port forwarding in VS Code
There are three ways to do it.
The --host
option
First, add --host
in the “scripts” section of package.json
like so.
{
"scripts": {
"dev": "vite --host"
}
}
Now, terminate the existing running instance and spin it up once again. Here’s what you will see.
As you can tell, Vite now gives you the ability to access the local instance on other devices under the same network through an IP-based URL like so.
Network: http://192.168.0.xxx:3000/
The Vite config
The other option is to add the following configuration in the vite.config.js
file like so.
server: {
host: true
}
Using --host
in CLI
Lastly, if you want to expose the instance on a one-off basis, you can use the --host
option with the npm run dev
command like so.
$ npm run dev -- --host
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.