Webpack Dev Server React Content Security Policy Error
If you’re running your single-page app on webpack-dev-server and encountering a Content Security Policy (CSP) error, you’re not alone. This error occurs when the server settings block the loading of a resource on the page, and it can be frustrating to debug. Fortunately, there are a few solutions you can try to resolve this issue.
Solution 1: Update your webpack configuration
To fix the Content Security Policy error, you need to make some changes to your webpack configuration file. Open your webpack.config.js file and add the following lines:
output: {
publicPath: '/'
},
devServer: {
historyApiFallback: true
}
The publicPath
option ensures that all the assets are served from the root path, while the historyApiFallback
option enables server-side routing, allowing you to reload or directly access specific URLs without getting the “Cannot GET” error.
Solution 2: Configure webpack-dev-server
If you prefer configuring webpack-dev-server directly from the command line, you can use the following command:
webpack-dev-server --history-api-fallback
This command starts the dev server with the necessary history API fallback option, ensuring that URL routing works correctly.
Solution 3: Check Rails and Webpacker integration
If you’re using Rails and Webpacker, the Content Security Policy error can also be related to the initializer configuration. Open the config/initializers/content_security_policy.rb
file and make sure that the line:
policy.connect_src :https, :self, 'http://localhost:8080', 'ws://localhost:8080' # example configuration
is using the correct protocol (either :http
or :https
) based on your development environment settings.
Solution 4: Remove contentBase from webpack.config.js
In some cases, removing the contentBase
line from the devServer
configuration in your webpack.config.js
file can resolve the issue. Update your file to look like this:
devServer: {
...
contentBase: false,
},
By setting contentBase
to false
, you avoid any potential conflicts that might interfere with the Content Security Policy.
With these solutions, you should be able to fix the Content Security Policy error and load any URLs in your single-page app without encountering the “Cannot GET” error. Choose the solution that best fits your setup, apply the necessary changes, and enjoy seamless development with webpack-dev-server.