Serving webpack dev server from a specific IP address - javascript

I'm trying to switch from localhost to a specific IP address, but I keep getting this error:
listen EADDRNOTAVAIL 192.168.1.139:8000
webpack.config.js
devServer: {
host: '192.168.1.139',
port: '8000',
compress: true,
}

The error you encountered:
listen EADDRNOTAVAIL 192.168.1.139:8000
Throws due to binding to already used port, it means 8000 is currently being managed eg. from another application (You must change a port or you must kill a process).
For your case of making local IP address binded as host it is possible for example via npm/yarn start:
"start": "webpack-dev-server --inline --port 8080 --host 192.168.1.139 --content-base ."
Assuming your machine's local IP is 192.168.1.139.
Based on Snippet from issue #147 webpack-dev-server.

As you are trying to map to a differrent ip : You need an entry in your hosts file as well to point that to localhost.
add the below in to your hosts file
127.0.0.1 192.168.1.139

Related

Vue CLI run serve always running on localhost

I have a vue.js project created with Vue CLI and npm run serveit always run on localhost.
I want to access from my phone (another IP inside the same network), so I want the serve to run on 0.0.0.0. I tried adding the vue.config.js file and setting the host:
module.exports = {
publicPath: '/',
devServer: {
host: '0.0.0.0',
port: 8080
}
}
Changing the port works fine, but the host override is ignored. This is the output of serve:
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.0.21:8080/
At first I thought it was being ignored, so I tried setting the host to 0.0.0.1 and the output is "correct", so the file is not ignored, only the 0.0.0.0 is being changed to localhost:
App running at:
- Local: http://0.0.0.1:8080/
- Network: http://0.0.0.1:8080/
I saw in some forums that devServer has a public option to set the URL, but if I try setting pubic: 'http://0.0.0.0:8080/' I get an error:
> npm run serve
Debugger attached.
> vue-model-viewer#0.1.0 serve <my project path>
> vue-cli-service serve
Debugger attached.
INFO Starting development server...
ERROR ValidationError: webpack Dev Server Invalid Options
options should NOT have additional properties
ValidationError: webpack Dev Server Invalid Options
options should NOT have additional properties
I need to run the server on 0.0.0.0 so I can test it on my phone.
Any help will be very appreciated.
You shouldn't need to run it on 0.0.0.0 from your local machine to test it on your phone. As long as the port on which it's running is open to external traffic and your phone is connected to your LAN via wifi, you can just put the IP address of your computer and the port # in as the URL.

nuxt.js - unable to define host and port

nuxt.js always defaults to localhost despite host being defined as frontend.gradez.loc in nuxt.config.js
Contents of nuxt.config.js:
server: {
host: 'frontend.gradez.loc',
port: 3000
},
Contents of package.json:
"config": {
"nuxt": {
"host": "frontend.gradez.loc",
"port": "3000"
}
}
nuxt launch script as dev:
"dev": "nuxt --hostname frontend.gradez.loc --port 3000",
For some odd reason when starting the development script it always defaults to: Listening on: http://localhost:3000/
I tried to do exactly the same on react and the only thing I had to do was create a .env file and inside it I added host=frontend.gradez.loc and it worked just like that.
To create your server, under the hood Nuxt uses Node's http.createServer, then calls listen({ host, port }) on that server.
So if on your local machine the hostname frontend.gradez.loc is mapped to 127.0.0.1, which I assume is the case, then that server is running on the IP 127.0.0.1.
To create the url you see printed in Listening on..., Nuxt gets the IP of that underlying server, and maps it back to a hostname string. It statically maps the IP 127.0.0.1 to the string 'localhost', so no matter what host you configure, if it maps to 127.0.0.1 then Nuxt will always map that to localhost in that url. The code that does this is here.
There's nothing incorrect per-se about reporting the server is running on localhost:3000 rather than frontend.gradez.loc:3000. It's literally true, in a networking sense, because both ultimately point to 127.0.0.1:3000. So nothing is broken here from the perspective of the dev server, it's working as designed.
I'm not sure if you have anything automatically loading that url in the browser when you start the server - if so I can see how this is inconvenient from the perspective of other things in your workflow coupled to that hostname such as cookies, proxy servers etc - but if you manually type frontend.gradez.loc:3000 into your browser everything will just work.

Angular/CLI: How to change the port for auto reload?

As I understand when running ng serve the Angular app polls the dev server to find out if a reload is necessary. This server is expected to live on port 4200 (default).
I run a dev environment with multiple docker container to keep things nice and isolated. So some of my angular apps listen on different ports. This seems to lead to the following error message appearing in my browser console every couple of seconds:
zone.js:2744 GET http://localhost:4200/sockjs-node/info?t=1518533495440 net::ERR_EMPTY_RESPONSE
Where can I change the configuration to point the live reload client in the correct direction? angular-cli.json doesn't seem to do anything.
I found the solution. You have to start ng serve with the --public-host option (aliases: --live-reload-client). So I adapted my start command in the package.json from
"start": "ng serve --host 0.0.0.0"
to
"start": "ng serve --host 0.0.0.0 --live-reload-client http://localhost:4400"
The whole point is that I don't want to change the port of the dev server itself. It should run inside the Docker container on port 4200. But port 4200 is mapped in Docker to the outside port 4400 (in my case). I call http://localhost:4400 to run the app in my browser and the reload client should also call http://localhost:4400 for updates. But it called http://localhost:4200. With the --live-reload-client option everything works.
You can configure the default HTTP port and the one used by the LiveReload server with two command-line options :
ng serve --host 0.0.0.0 --port 4201 --live-reload-port 49153
It seems --live-reload-port is no longer used in newer versions.
Live reload port is identical to development server port.
So setting --port 4201 will use 4201 as the live reload port.
You can change the port using --port
ng serve --port 4201
Will start the server on port 4201
While running your application instance use this command:
ng serve --port 123
instead of:
ng serve
whilst changing in package.json doesn't make any impact.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

I am using as an environment, a Cloud9.io ubuntu VM Online IDE and I have reduced by troubleshooting this error to just running the app with Webpack dev server.
I launch it with:
webpack-dev-server -d --watch --history-api-fallback --host $IP --port $PORT
$IP is a variable that has the host address
$PORT has the port number.
I am instructed to use these vars when deploying an app in Cloud 9, as they have the default IP and PORT info.
The server boots up and compiles the code, no problem, it is not showing me the index file though. Only a blank screen with "Invalid Host header" as text.
This is the Request:
GET / HTTP/1.1
Host: store-client-nestroia1.c9users.io
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
This is my package.json:
{
"name": "workspace",
"version": "0.0.0",
"scripts": {
"dev": "webpack -d --watch",
"server": "webpack-dev-server -d --watch --history-api-fallback --host $IP --port $PORT",
"build": "webpack --config webpack.config.js"
},
"author": "Artur Vieira",
"license": "ISC",
"dependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-0": "^6.24.1",
"file-loader": "^0.11.1",
"node-fetch": "^1.6.3",
"react": "^15.5.4",
"react-bootstrap": "^0.30.9",
"react-dom": "^15.5.4",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"url-loader": "^0.5.8",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4",
"whatwg-fetch": "^2.0.3"
}
}
This is the webpack.config.js:
const path = require('path');
module.exports = {
entry: ['whatwg-fetch', "./app/_app.jsx"], // string | object | array
// Here the application starts executing
// and webpack starts bundling
output: {
// options related to how webpack emits results
path: path.resolve(__dirname, "./public"), // string
// the target directory for all output files
// must be an absolute path (use the Node.js path module)
filename: "bundle.js", // string
// the filename template for entry chunks
publicPath: "/public/", // string
// the url to the output directory resolved relative to the HTML page
},
module: {
// configuration regarding modules
rules: [
// rules for modules (configure loaders, parser options, etc.)
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "./app")
],
exclude: [
path.resolve(__dirname, "./node_modules")
],
loader: "babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0",
// the loader which should be applied, it'll be resolved relative to the context
// -loader suffix is no longer optional in webpack2 for clarity reasons
// see webpack 1 upgrade guide
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|jpg|jpeg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000
}
}
]
},
devServer: {
compress: true
}
}
Webpack dev server is returning this because of my host setup. In webpack-dev-server/lib/Server.js line 60. From https://github.com/webpack/webpack-dev-server
My question is how do I setup to correctly pass this check. Any help would be greatly appreciated.
The problem occurs because webpack-dev-server 2.4.4 adds a host check. You can disable it by adding this to your webpack config:
devServer: {
compress: true,
disableHostCheck: true, // That solved it
}
Please note, this fix is insecure.
Please see this answer for a secure solution.
The option was refactored in version 4.0.0. The allowedHosts option should now be used:
devServer: {
allowedHosts: "all"
}
I found out, that I need to set the public property of devServer, to my request's host value. Being that it will be displayed at that external address.
So I needed this in my webpack.config.js
devServer: {
compress: true,
public: 'store-client-nestroia1.c9users.io' // That solved it
}
Another solution is using it on the CLI:
webpack-dev-server --public $C9_HOSTNAME <-- var for Cloud9 external IP
This is what worked for me:
Add allowedHosts under devServer in your webpack.config.js:
devServer: {
compress: true,
inline: true,
port: '8080',
allowedHosts: [
'.amazonaws.com'
]
},
I did not need to use the --host or --public params.
Rather than editing the webpack config file, the easier way to disable the host check is by adding a .env file to your root folder and putting this:
DANGEROUSLY_DISABLE_HOST_CHECK=true
As the variable name implies, disabling it is insecure and is only advisable to use only in dev environment.
Add this config to your webpack config file when using webpack-dev-server (you can still specify the host as 0.0.0.0).
devServer: {
disableHostCheck: true,
host: '0.0.0.0',
port: 3000
}
The more secure option would be to add allowedHosts to your Webpack config like this:
module.exports = {
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
The array contains all allowed host, you can also specify subdomians. check out more here
If you have not ejected from CRA yet, you can't easily modify your webpack config. The config file is hidden in node_modules/react_scripts/config/webpackDevServer.config.js. You are discouraged to change that config.
Instead, you can just set the environment variable DANGEROUSLY_DISABLE_HOST_CHECK to true to disable the host check:
DANGEROUSLY_DISABLE_HOST_CHECK=true yarn start
# or the equivalent npm command
on package.json, on "scripts", add the param --disableHostCheck=true
Like:
"scripts": {
"start": "ng serve --host=0.0.0.0 --configuration=dev --disableHostCheck=true"
}
If you are running webpack-dev-server in a container and are sending requests to it via its container name, you will get this error. To allow requests from other containers on the same network, simply provide the container name (or whatever name is used to resolve the container) using the --public option. This is better than disabling the security check entirely.
In my case, I was running webpack-dev-server in a container named assets with docker-compose. I changed the start command to this:
webpack-dev-server --mode development --host 0.0.0.0 --public assets
And the other container was now able to make requests via http://assets:5000.
If you are using create-react-app on C9 just run this command to start
npm run start --public $C9_HOSTNAME
And access the app from whatever your hostname is (eg type $C_HOSTNAME in the terminal to get the hostname)
While using the default behavior (no config file) with webpack 5 related to this post: [https://stackoverflow.com/a/65268634/2544762`]
"scripts": {
"dev": "webpack serve --mode development --env development --hot --port 3000"
...
...
},
"devDependencies": {
...
"webpack": "^5.10.1",
"webpack-cli": "^4.2.0"
},
With webpack 5 help webpack serve --help:
Usage: webpack serve|server|s [entries...] [options]
Run the webpack dev server.
Options:
-c, --config <value...> Provide path to a webpack configuration file e.g.
./webpack.config.js.
--config-name <value...> Name of the configuration to use.
-m, --merge Merge two or more configurations using
'webpack-merge'.
--env <value...> Environment passed to the configuration when it
is a function.
--node-env <value> Sets process.env.NODE_ENV to the specified value.
--progress [value] Print compilation progress during build.
-j, --json [value] Prints result as JSON or store it in a file.
-d, --devtool <value> Determine source maps to use.
--no-devtool Do not generate source maps.
--entry <value...> The entry point(s) of your application e.g.
./src/main.js.
--mode <value> Defines the mode to pass to webpack.
--name <value> Name of the configuration. Used when loading
multiple configurations.
-o, --output-path <value> Output location of the file generated by webpack
e.g. ./dist/.
--stats [value] It instructs webpack on how to treat the stats
e.g. verbose.
--no-stats Disable stats output.
-t, --target <value...> Sets the build target e.g. node.
--no-target Negative 'target' option.
--watch-options-stdin Stop watching when stdin stream has ended.
--no-watch-options-stdin Do not stop watching when stdin stream has ended.
--bonjour Broadcasts the server via ZeroConf networking on
start
--lazy Lazy
--liveReload Enables/Disables live reloading on changing files
--serveIndex Enables/Disables serveIndex middleware
--inline Inline mode (set to false to disable including
client scripts like livereload)
--profile Print compilation profile data for progress steps
--progress Print compilation progress in percentage
--hot-only Do not refresh page if HMR fails
--stdin close when stdin ends
--open [value] Open the default browser, or optionally specify a
browser name
--useLocalIp Open default browser with local IP
--open-page <value> Open default browser with the specified page
--client-log-level <value> Log level in the browser (trace, debug, info,
warn, error or silent)
--https HTTPS
--http2 HTTP/2, must be used with HTTPS
--key <value> Path to a SSL key.
--cert <value> Path to a SSL certificate.
--cacert <value> Path to a SSL CA certificate.
--pfx <value> Path to a SSL pfx file.
--pfx-passphrase <value> Passphrase for pfx file.
--content-base <value> A directory or URL to serve HTML content from.
--watch-content-base Enable live-reloading of the content-base.
--history-api-fallback Fallback to /index.html for Single Page
Applications.
--compress Enable gzip compression
--port <value> The port
--disable-host-check Will not check the host
--socket <value> Socket to listen
--public <value> The public hostname/ip address of the server
--host <value> The hostname/ip address the server will bind to
--allowed-hosts <value...> A list of hosts that are allowed to access the
dev server, separated by spaces
Global options:
--color Enable colors on console.
--no-color Disable colors on console.
-v, --version Output the version number of 'webpack',
'webpack-cli' and 'webpack-dev-server' and
commands.
-h, --help [verbose] Display help for commands and options.
To see list of all supported commands and options run 'webpack --help=verbose'.
Webpack documentation: https://webpack.js.org/.
CLI documentation: https://webpack.js.org/api/cli/.
Made with ♥ by the webpack team.
Done in 0.44s.
Solution
So, just add --disable-host-check with the webpack serve command do the trick.
Hello React Developers,
Instead of doing this
disableHostCheck: true, in webpackDevServer.config.js. You can easily solve 'invalid host headers' error by adding a .env file to you project, add the variables HOST=0.0.0.0 and DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file. If you want to make changes in webpackDevServer.config.js, you need to extract the react-scripts by using 'npm run eject' which is not recommended to do it. So the better solution is adding above mentioned variables in .env file of your project.
Happy Coding :)
I just experienced this issue while using the Windows Subsystem for Linux (WSL2), so I will also share this solution.
My objective was to render the output from webpack both at wsl:3000 and localhost:3000, thereby creating an alternate local endpoint.
As you might expect, this initially caused the "Invalid Host header" error to arise. Nothing seemed to help until I added the devServer config option shown below.
module.exports = {
//...
devServer: {
proxy: [
{
context: ['http://wsl:3000'],
target: 'http://localhost:3000',
},
],
},
}
This fixed the "bug" without introducing any security risks.
Reference: webpack DevServer docs
I am using nginx running inside of a docker container to route traffic based on the url.
Adding the following two lines of code in the nginx config file fixed the error Invalid Host header for me. See below for the config file(default.conf).
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
First the following is my simple two liner Dockerfile to create the nginx container and then configure it with routing.
FROM nginx
COPY ./default.conf /etc/nginx/conf.d/default.conf
So when the image is built, the default.conf file is copied to the configuration directory inside of the nginx container.
Next the default.conf file looks as follows.
upstream ui {
# The ui service below is a ui app running inside of a container. Inside of the container, the ui app is listening on port 3000.
server ui:3000;
}
upstream node-app {
# The node-app service below is a server app running inside of a container. Inside of the container, the server is listening on port 8080.
server node-app:8080;
}
server {
listen 80;
location / {
# The root path, with is '/' will routed to ui.
proxy_pass http://ui;
################## HERE IS THE FIX ##################
# Adding the following two lines of code finally made the error "Invalid Host header" go away.
# The following two headers will pass the client ip address to the upstream server
# See upstream ui at the very begining of this file.
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
}
location /api {
# Requests that have '/api' in the path are rounted to the express server.
proxy_pass http://node-app;
}
}
#
Finally, if you want to take a look at my docker compose file, which has all the services(including nginx), here it is
version: '3'
services:
# This is the nginx service.
proxy:
build:
# The proxy folder will have the Dockerfile and the default.conf file I mentioned above.
context: ./proxy
ports:
- 7081:80
redis-server:
image: 'redis'
node-app:
restart: on-failure
build:
context: ./globoappserver
ports:
- "9080:8080"
container_name: api-server
ui:
build:
context: ./globo-react-app-ui
environment:
- CHOKIDAR_USEPOLLING=true
ports:
- "7000:3000"
stdin_open: true
volumes:
- ./globo-react-app-ui:/usr/app
postgres:
image: postgres
volumes:
- postgres:/var/lib/postgresql/data
- ./init-database.sql:/docker-entrypoint-initdb.d/init-database.sql
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
volumes:
postgres:
When an HTTP request is made, by default, browsers/clients include the "Host" (from the URL) as part of the headers of the raw HTTP request. As part of an extra security/sanity check that is now commonplace, that Host header must match what is expected by the HTTP server for the server to send you back what you expect.
By default, the Webpack Dev Server (WDS) only accepts incoming HTTP requests with Host header that matches some common hostnames like localhost. When a request comes in with an unexpected Host header, the server still needs to respond with something. So it does the minimum it can: send a response with a standard HTTP error code and a human readable message in the HTML: "Invalid Host header".
Now, as for how to fix this issue, there are basically two options. Tell WDS to accept more (or all) "Host" headers or fix the Host header that is sent with the HTTP request.
Configure Webpack
Generally, it's easier (and more correct) to tell the WDS configuration to allow more "Host"names to be used. By default, WDS only accepts connections from the local development machine and so, by default, only needs to support the hostname localhost. Most commonly this "Invalid Host header" issue comes up when trying to server to other clients on the network. After adding host: '0.0.0.0' to the devServer configuration, WDS needs to be told which names might be used by clients to talk to it. require('os').hostname() is usually (one of) the hostnames but other names could be just as valid. Because of this, WDS accepts a list of allowed names.
module.exports = {
//...
devServer: {
allowedHosts: [
require('os').hostname(),
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
However, sometimes getting this list correct is more trouble than it's worth and it's good enough to just tell WDS to ignore the Host header check. In Webpack 4, it was the disableHostCheck option. In Webpack 5, the allowedHosts option could be set to the single string 'all' (no array).
Create React App (CRA)
The popular package create-react-app uses Webpack internally. CRA has an extra environment variable just to override this particular setting: DANGEROUSLY_DISABLE_HOST_CHECK=true.
Send different Host header
If changing the configuration of Webpack is not possible, the other way to get around this is to change the configuration of the client.
One trick is to use the hosts file on the client machine such that the hostname needed maps to the server's IP.
More common is when a reverse proxy is in-front of WDS. Different proxies have different defaults for the request that's sent to the backend (WDS). You might need to specifically add the Host header to the requests to the backend as VivekDev's answer suggests.
Anyone coming here in 2021 on webpack-dev-server v4+,
allowedHosts and disableHostsCheck were removed in favor of allowedHosts: 'all'
To get rid of the error, change your devServer to this:
devServer: {
compress: true,
allowedHosts: 'all'
}
I solved this problem by adding proxying of the host header in the nginx configuration, like this:
server {
listen 80;
server_name localhost:3000;
location / {
proxy_pass http://myservice:8080/;
proxy_set_header HOST $host;
proxy_set_header Referer $http_referer;
}
}
I added that:
proxy_set_header HOST $host;
proxy_set_header Referer $http_referer;
Since webpack-dev-server 4 you need to add this to your config:
devServer: {
firewall: false,
}
note for vue-cli users:
put a file vue.config.js in the root, with the same lines:
module.exports = {
configureWebpack: {
devServer: {
public: '0.0.0.0:8080',
host: '0.0.0.0',
disableHostCheck: true,
}
}
};
This may happen under two situations:
When you run your webpack-dev-server in cloud-9 or any other online IDE other than localhost.
When you want to run the dev mode on mobile or quickly share the web app with another person via a public URL for your localhost (e.g. using ngrok). For security purposes, you cannot externally access your webpack-dev-server.
You can achieve this in the following way:
devServer: {
allowedHosts: 'auto' | 'all' | Array[string]
}
If you have no regard for security, you may set allowedHosts to 'all'. (Not recommended, though)
If you use some-host-url to make public URLs, you can do as follows:
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com'
]
}
For more info: Official doc
I tried the suggestions above but the following solution didn't work for me:
devServer: {
allowedHosts: 'auto' | 'all' | Array[string]
}
The following solution works for me:
devServer: {
disableHostCheck: true
}
For webpack-dev-server 4.7 you can use --allowed-hosts all
npx webpack serve --open --allowed-hosts all
Since I am starting the server with npm start, I need to alter package.json as follows,
"scripts": {
"start": "webpack-dev-server --progress --disableHostCheck"
},
Try adding the following in your webpack.config.js file. This worked for me.
devServer: {
allowedHosts: [yourhostname.com]
}

How to get access to webpack-dev-server from devices in local network?

There is some webpack dev server config (it's part of the whole config):
config.devServer = {
contentBase: './' + (options.publicFolder ? options.publicFolder : 'public'),
stats: {
modules: false,
cached: false,
colors: true,
chunk: false
},
proxy: [{
path: /^\/api\/(.*)/,
target: options.proxyApiTarget,
rewrite: rewriteUrl('/$1'),
changeOrigin: true
}]
};
function rewriteUrl(replacePath) {
return function (req, opt) { // gets called with request and proxy object
var queryIndex = req.url.indexOf('?');
var query = queryIndex >= 0 ? req.url.substr(queryIndex) : "";
req.url = req.path.replace(opt.path, replacePath) + query;
console.log("rewriting ", req.originalUrl, req.url);
};
}
I execute webpack with the following command:
node node_modules/webpack-dev-server/bin/webpack-dev-server.js --host 0.0.0.0 --history-api-fallback --debug --inline --progress --config config/webpack.app.dev.js
I can get access to dev server using http://localhost:8080 on my local machine, but I also want to get access to my server from my mobile, tablet (they are in the same Wi-Fi network).
How can I enable it? Thanks!
(If you're on a Mac and network like mine.)
Run webpack-dev-server with --host 0.0.0.0 — this lets the server listen for requests from the network, not just localhost.
Find your computer's address on the network. In terminal, type ifconfig and look for the en1 section or the one with something like inet 192.168.1.111
In your mobile device on the same network, visit http://192.168.1.111:8080 and enjoy hot reloading dev bliss.
You can set your ip address directly in webpack config file:
devServer: {
host: '0.0.0.0',//your ip address
port: 8080,
disableHostCheck: true,
...
}
It may not be the perfect solution but I think you can use ngrok for this.
Ngrok can help you expose a local web server to the internet.
You can point ngrok at your local dev server and then configure your app to use the ngrok URL.
e.g Suppose your server is running on port 8080. You can use ngrok to expose that to outer world via running
./ngrok http 8080
Good thing about ngrok is that it provides a more secure https version of exposed url which you give to any other person in the world to test or show your work.
Also it has lots of customization available in the command such as set a user friendly hostname instead of random string in the exposed url and lots of other thing.
If you just want to open your website to check mobile responsiveness you should go for browersync.
For me, what helped eventually was adding this to the webpack-dev-server config:
new webpackDev(webpack(config), {
public: require('os').hostname().toLowerCase() + ':3000'
...
})
and then also changing babel's webpack.config.js file:
module.exports = {
entry: [
'webpack-dev-server/client?http://' + require('os').hostname().toLowerCase() + ':3000',
...
]
...
}
Now just get your computer hostname (hostname on OSX's terminal), add the port you defined, and you're good to go on mobile.
Compared to ngrok.io, this solution will also let you use react's hot reloading module on mobile.
I could not comment in order to add additional information to forresto's answer, but here in the future (2019) you'll need to add a --public flag due to a security vulnerability with --host 0.0.0.0 alone. Check out this comment for more details.
In order to avoid "responding to other answers" as an answer here's forresto's advice plus the additional details you'll need to make this work:
Add both:
--host 0.0.0.0
and
--public <your-host>:<port>
where your-host is the hostname (for me it is (name)s-macbook-pro.local)) and port is whatever port you're trying to access (again, for me it's 8081).
So here's what my package.json looks like:
"scripts": {
...
"start:webpack": "node_modules/.bin/webpack-dev-server --host 0.0.0.0 --public <name>s-macbook-pro.local:8081",
...
},
I found this thread while searching for a solution that would satisfy the following requirements:
automatically open URL using the public IP. For example, http://192.168.86.173:8080. So it could be copied from the browser and sent to another device in the network.
dev server is available in the local network.
Webpack 4
devServer: {
host: '0.0.0.0',
useLocalIp: true,
}
Webpack 5
devServer: {
host: 'local-ip',
}
With webpack-dev-server v4.0.0+ you need
devServer: {
host: '0.0.0.0',
port: 8030,
allowedHosts: ['all'] // or use 'auto' for slight more security
}
If you tried everything stated in the other answers here, without success... also make sure there's no firewall running on you machine(s) or open the needed ports on it.

Categories