Routes Are Not Valid When Using Basename Property Of Router On Production Mode
I'm using this Router:
import {BrowserRouter as Router, Route, Switch } from "react-router-dom";
<Router basename={process.env.REACT_APP_ROUTER_BASE || '/MyApp'}>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/login" component={Login} />
{/*<Redirect path="*" to="/" />*/}
</Switch>
</Router>
When working with dev mode (npm start), it's working and redirecting as expected.
When working with production mode (npm build --> copy the output of build to WebContent folder on a war to be deployed on tomcat), it behaves differently:
- http://host:port/MyApp is working fine, and routing using the app is fine too
- routing manually by typing the route value on the browser, e.g. http://host:port/MyApp/login is giving: Page can't be found.
(Note: typing the route manually in dev mode working fine)
Why it differs? How it can be solved?
What I had tried:
Reference: React routing not working while manually changing URL | React-router 4
adding devServer entry (with historyApiFallback: true) to my webpack.config.prod.json:
export default {
resolve: {
extensions: ['*', '.js', '.jsx', '.json'],
// To support react-hot-loader
alias: {
'react-dom': '@hot-loader/react-dom'
}
},
devtool: 'source-map', // more info:https://webpack.js.org/guides/production/#source-mapping and https://webpack.js.org/configuration/devtool/,
devServer: {
historyApiFallback: true,
},
Answer
What historyApiFallback: true
does is it renders index.html
if the requested file doesn't exist. Your production webserver is not doing this, so when it attempts to load /MyApp/login
, it see that there is no file called /MyApp/login
(or /MyApp/login/index.html
depending on configuration) and returns a 404.
Since React Router is handling your routing logic client side, you need to set up your webserver to fallback to delivering index.html
if it can't find a page.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?