react-router does not work in production and surge deployments

isuruAb picture isuruAb · Jun 12, 2017 · Viewed 19.3k times · Source

My react application is working fine on localhost but when after i deployed it in gh-pages or surge it does not give me to move among pages using URL.

  • This is the project repo link
  • Demo url here

users can go to signup page by clicking menuItem of top right corner. but If user use http://chat.susi.ai/signup/ URL, it gives 404 page

I tried several solutions from internet but didn't work.

Next question is : I created a 404 page to show up when user tries to move to broken links.It works fine in localhost. but not in production. I tried this solution but nothing changed.

this is part of my index.js file

const App = () => (
    <Router history={hashHistory}>
        <MuiThemeProvider>
            <Switch>
                <Route exact path="/" component={ChatApp} />
                <Route exact path="/signup" component={SignUp} />
                <Route exact path="/logout" component={Logout} />
                <Route exact path="/forgotpwd" component={ForgotPassword} />
                <Route exact path="*" component={NotFound} />

            </Switch>
        </MuiThemeProvider>
    </Router>
);

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

If someone can suggest good solution with sample code for my problems that would be really helpful for me.

Answer

Jonny Buchanan picture Jonny Buchanan · Jun 12, 2017

This is happening because users aren't being served the index.html which bootstraps your app when they visit those URLs directly.

For surge, you can add a 200.html file which contains the same contents as the index.html you're deploying (or just rename it to 200.html) - this will then be served to users at any URL they visit which doesn't correspond to a static file, allowing your app to start running.


Edit: looks like you're using create-react-app. This works when you're developing locally because create-react-app's react-scripts package handles serving your index.html as a fallback for these requests.

The react-scripts user guide has sections on how to handle this when deploying to GitHub Pages and surge.sh (as above).