reactjsreduxreact-routerbrowser-history

Implementing history-api-fallback for Webpack Production environment


My stack is React/Redux as frontend together with React Router v4 and Firebase Hosting as backend.

Like many others, I also faced the issue of meeting the 404 page not found when users refreshed at a page other than the root URL like https://example.com/about or manually key in the URL https://example.com/about.

I researched many websites and HashBrowser seem to be a workaround for this problem but it is not a complete solution. It does not bring the user to the correct page but instead render the root URL component. Not good enough. Using historyApiFallback: true for production environment seemed to be a bad idea too.

I saw this package, connect-history-api-fallback but it seems to be for a express app.

How can I implement this package in my React app while using Firebase to host my website? Or are there other solutions?


Solution

  • I found the solution. This only applies to people deploying React App, using Firebase Hosting to host your single page application. (should work for Angularjs/Vuejs too)

    When you first run firebase init, they ask if you want to configure as a single-page app, make sure you select yes. The end result is that they will write this portion to your firebase.json file,

    "rewrites": [ {
      "source": "**",
      "destination": "/index.html"
    } 
    

    it works the same as having

    devServer: {
        historyApiFallback: true
    },
    

    in your webpack.config.js file to redirect all URLs to the root URL of your application. ("/")

    Full implementation of the firebase.json file may look like this,

    {
      "hosting": {
        "public": "public",
        "rewrites": [{
          "source": "**",
          "destination": "/index.html"
        }],
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ]
      }
    }
    

    More information may be found in the Firebase Deployment Configuration Documentation.