Vite Server is running on 127.0.0.1 by default instead of localhost
Asked Answered
J

4

21

Whenever i run npm run dev, i get vite running on domain 127.0.0.1 by default.

How to make vite run on localhost instead?

Theses are my configs:

package.json:

  "scripts": {
    "dev": "vite --host=localhost",
    "build": "vite build",
    "preview": "vite preview"
  },

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: 'localhost',
    port: 3000
  }
})

vite console

Jewelljewelle answered 21/4, 2023 at 14:15 Comment(0)
S
20

This is intended. You can consult vite localhost behavior (read the note). To disable this behavior set dns.setDefaultResultOrder('verbatim') as explained there or upgrade Node.js to 17+. Also localhost

in your vite.config :

import { defineConfig } from 'vite'
import dns from 'dns'
import react from '@vitejs/plugin-react-swc'

dns.setDefaultResultOrder('verbatim')

export default defineConfig({
  plugins: [react()],
  server: {
    host: 'localhost',
    port: 3000
  }
})

Result:

vite console

Hope it answers to your question ! :)

Sideman answered 21/4, 2023 at 16:6 Comment(0)
J
9

An other alternative solution that works:

package.json:

 "scripts": {
    "dev": "vite --host",
    "build": "vite build",
    "preview": "vite preview"
  },

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: 'localhost',
    port: 3000
  }
})

result:

vite console

read more

Jewelljewelle answered 22/4, 2023 at 10:58 Comment(2)
Is there a way to prevent it from listening on the other network interfaces as well?Blackmon
To be clear this solution only change "dev": "vite --host", inside package.json file.Howlyn
C
3

Just faced the same problem and tried to use dns.setDefaultResultOrder('verbatim') solution but got TypeScript error:

Property 'setDefaultResultOrder' does not exist on type 'typeof import("dns")'

It's because I used Node 16 but have installed @types/node for Node 12. Just updated types package and everything is ok.

Also, I don't have to set port: 'localhost', just setDefaultResultOrder.

Containment answered 12/7, 2023 at 0:55 Comment(0)
H
0

Here is working solution to create and run a React hello world project with npm Vite.

mkdir react_dev
cd react_dev/
npm create vite@latest my-react-app -- --template react
cd my-react-app/
npm install 

To run project and expose to 0.0.0.0:5173 run below command.

$ npm run dev -- --host

https://mcmap.net/q/363069/-npm-run-dev-host-network-not-exposed

Howlyn answered 8/5 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.