React Router BrowserRouter Refresh 404 Apr 27th 2021 Words: 303

Problem

My simple react SPA using react-router as follows:

index.html

1
2
3
4
5
6
<!DOCTYPE html>
<html lang="en">
<body>
<div id="react-app"></div>
</body>
</html>

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import Home from './pages/Home';
import Profile from './pages/Profile';
import NotFound from "./pages/404";

ReactDOM.render((
<Router>
<Switch>
<Route exact path={"/"} component={Home}/>
<PrivateRoute path={"/profile"} component={Profile}/>
<Route path={"*"} component={NotFound}/>
</Switch>
</Router>
), document.getElementById("react-app"));

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// some options removed for simplicity

const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
entry: {
main: "./src/index.js"
},
output: {
clean: true,
filename: "[name].[contenthash].js",
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: "babel-loader",
}
]
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: {
minimize: true
}
}
]
}
]
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss']
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};

Solution

In the webpack config, add publicPath and historyApiFallBack:

1
2
3
4
5
6
7
8
output: {
clean: true,
filename: isDevelopment ? "[name].js" : "[name].[contenthash].js",
publicPath: "/"
},
devServer: {
historyApiFallback: true,
}

Reference

React-router v4 - cannot GET url