React Routing works in local machine but not Heroku
I actually came across this post first before 3 hours of searching through react-router and heroku documentation. For swyx, and anyone else having the same problem, I'll outline the minimum of what you need to do to get this working.
router.js - (Obviously change AppSplash and AppDemo to your components)
export default <Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={AppSplash}/>
<Route path="demo" component={AppDemo}/>
</Route>
</Router>
app.jsimport React, { Component } from 'react'
class App extends Component {
static propTypes = {
children: PropTypes.node
}
render() {
const { children } = this.props
return (
<div>
{children}
</div>
)
}
}
export default App
Create a new file in the root of your home directory and name it static.json. Put this into it. {
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
Push to heroku again. The routes should work this time. Explanation:
You need to modify Heroku's default webpack, otherwise the service gets confused with how to handle the client-side routing. Essentially what static.json does. The rest is just the correct way to handle the routing according to the 'react-router' documentation.
React Routing works in locally but not Heroku
Alrighty, I figured this out.
All I needed was to ensure that any request not relevant for my internal API, such as a GET
request via the address bar, is routed directly to my index.html
file which handles the dynamic routing via React Router. Seems obvious enough now.
Here is the final route in my app.js
:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build/index.html'));
});
React Router working on local but not work on real server
If you’re using Apache HTTP Server, you need to create a .htaccess file in the public folder that looks like this:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
It will get copied to the build folder when you run npm run build.
Related Topics
Get the Current Year in JavaScript
How to Send Images to Node Js with Axios
Understanding JavaScript Immutable Variable
JavaScript When to Use Prototypes
JavaScript Property with Three Dots (...)
How to Remove a Table Row with Jquery
Do We Need Semicolon at the End
How to Test for Nan in JavaScript
Conversion Between Utf-8 Arraybuffer and String
Implementing or in Firestore Query - Firebase Firestore
How to Know When I'Ve Stopped Scrolling
Prevent JavaScript Keydown Event from Being Handled Multiple Times While Held Down
Get Selected HTML in Browser via JavaScript
JavaScript Toisostring() Ignores Timezone Offset
Add Two Functions to Window.Onload
Understanding JavaScript Promise Object
Sort an Array by the "Levenshtein Distance" with Best Performance in JavaScript