jasan jasan - 2 months ago 13x
React JSX Question

How do I Serve a 404 page using firebase hosting for a React SPA?

I am currently using firebase hosting for my single page React application. I have also added a 404.html page to my public directory. My assumption was that this page would get served if a user enter an url that is not in my routes(using react-router), but there is no way for firebase to know if an url is valid or not, or is there. Currently if I enter something random after the / of my main app url the page just shows blank. Is this something i need to account for within my React app, if so HOW?


You can let the React Router take care of serving a 404 page on the client side. This is how you can setup:

var NotFound = React.createClass({
    render: function() {
        return (<h1>Page Not Found</h1>);

var App = React.createClass({
    render: function() {
        <Router history={browserHistory}>
            <Route path="/" component={App}>
                <Route path="first" component={SomeComponent}/>
                <Route path="second" component={SomeOtherComponent}/>
                <Route path="*" component={NotFound}/>


Note that the catch all route (*) should be the last so that React Router can try all others and finally get to this.

Here's a nice article that explains this.