React Routing Works in Local MAChine But Not Heroku

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.js

import 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



Leave a reply



Submit