运行在 HTTPS/Web Sockets 安全上的 Webpack 开发服务器

通常在开发人员模式下,Webpack 使用 HTTP 运行。通常有一个 Web 服务器通过 HTTP 和 webpack 在单独的端口上使用 HTTP/websockets 提供内容。

是否可以在 https 上运行 Web 服务器,在 https/websocket 上运行 webpack?

116189 次浏览

See the webpack docs

There is a flag you can add to the webpack-dev-server command

webpack-dev-server --https

While the above answer is correct for cli, if you are not in the CLI, you could do something like this (in a gulp task):

var WebpackDevServer = require('webpack-dev-server');


new WebpackDevServer(webpack(WebpackDevConfig), {
https: true,
hot: true,
watch: true,
contentBase: path.join(__dirname, 'src'),
historyApiFallback: true
}).listen(1337, 'localhost', function(err, result) {
if (err) {
console.log(err);
}
console.log('Dev server running at https://localhost:1337');
});

this for TEST environment only:

you need to configure your webpack-dev-server as follows:

webpack-dev-server --https --cert ./cert.pem --key ./key.pem

The easiest work around is to generate a key with no passphrase (I don't know the security consequences of this! but this is for test only) .

To take the passphrase out of your key use this command:

$ openssl rsa -in key.pem -out newKey.pem

and use the new key in the previews configuration line

With webpack-dev-server --https you create a self-signed certificate. But it works not for all use cases.

Browsers will ask you for a security exception and show in the url bar that connection is not secure.

Therefore it is recommended to create a locally trusted development certificate for localhost with mkcert

Then use it via CLI:

webpack-dev-server --https --key C:/Users/User/localhost-key.pem --cert C:/Users/User/localhost.pem --cacert C:/Users/User/AppData/Local/mkcert/rootCA.pem

or configure devServer.https option in webpack.config.js:

devServer: {
https: {
key: fs.readFileSync('C:/Users/User/localhost-key.pem'),
cert: fs.readFileSync('C:/Users/User/localhost.pem'),
ca: fs.readFileSync('C:/Users/User/AppData/Local/mkcert/rootCA.pem')
}
}

mkcert creates .pem files in Unix format by default. So if you're on Windows you'll probably need convert them to Windows format using e.g. Notepad++

In my case I had to run all these commands to get the certificate:

openssl genrsa -out private.key 4096
openssl req -new -sha256 -out private.csr -key private.key
openssl x509 -req -days 3650 -in private.csr -signkey private.key -out private.crt -extensions req_ext
openssl x509 -in private.crt -out private.pem -outform PEM

And then finally:

npm run dev -- --open --https --cert private.pem --key private.key

I'm working on react project, Now wanted to add SSL certificate on this project and run my website with https so have followed below step:

  1. In add https in webpack.config.js

     devServer:{
    
    
    https: true,
    host: '0.0.0.0', // you can change this ip with your ip
    port: 443,       // ssl defult port number
    inline: true,
    
    
    historyApiFallback: true,
    publicPath: '/',
    contentBase: './dist',
    disableHostCheck: true
    }
    
  2. Add SSL public certificate on package.json file If you didn't want to add a certificate on your package.json file then you have to add it on your webpack.config.js it is mandatory to add your certificate in your project either you can it on package.json file or webpack.config.js

For Package.json

scripts: {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"start": "webpack-dev-server  --open --https --cert /path/to/private.crt --key /path/to/private.key"


}

OR webpack.config.js

 devServer:{


https: true,
host: '0.0.0.0', // you can change this ip with your ip
port: 443,       // ssl defult port number
inline: true,
https: {
key: fs.readFileSync('/path/to/private.pem'),
cert: fs.readFileSync('/path/to/private.pem'),
ca: fs.readFileSync('/path/to/private.pem')
}
historyApiFallback: true,
publicPath: '/',
contentBase: './dist',
disableHostCheck: true
}
  1. Run npm start command on a terminal or you can also use pm2 start npm -- start

Tested on Windows (04/22/2021). Easy (no installations required).

1. Project configuration

In your project root run in Powershell (or CMD):

npx mkcert create-ca
npx mkcert create-cert

Your webpack.config.js:

devServer: {
// ...
https: {
key: fs.readFileSync("cert.key"),
cert: fs.readFileSync("cert.crt"),
ca: fs.readFileSync("ca.crt"),
},
// ....
},

2. Install certificate

Double-click on ca.crt > Install Certificate > ...

Install Certificate

... > Current User > Place all certificates in the following store > Trusted Root Certification Authorities > ...

Install Certificate > Store

... > Finish > Yes

Install Certificate > Finish

3. Check correct installation

Start > Type: "cert" > Manage User Certificates > ...

Manage User Certificates

... > Trusted Root Certification Authorities > Certificates > Test CA

Manage User Certificates > Check

4. Reload & Test

Reload your browser, Start yout webpack dev server and check the SSL Certificate validity:

Test Test > Certificate

Additional steps

If you get this error:

Host check error

You can add this configuration to your webpack.config.js:

devServer: {
// ...
// https: { ... }
disableHostCheck: true,
// ....
},

For more info:

https://webpack.js.org/configuration/dev-server/#devserverhttps

https://www.npmjs.com/package/mkcert

Had similar case when webapp was served from docker container which internally uses http, but traefik is serving app though https (multiple ports: 4000, 3000), so socket client was trying to connect to http://my.app.url:3000.

After spending a few hours to figure out a solution, came up with this in webpack 5:

devServer: {
client: {
port: ' ', <--must be empty to eliminate the 3000 port for connecting to socket client
},
devMiddleware: {
writeToDisk: true,
},
transportMode: 'sockjs',
port: 3000, // port which is dev server opening for the sockets
...(process.env.DOCKER_DEV && {
host: '0.0.0.0',
firewall: false,
public: 'https://my.app.url', <-- HTTPS here
}),
},