3

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?

Seng Wee
  • 534
  • 9
  • 20
  • Did you use the firebase-cli to deploy? If you did, then it will ask if you want to deploy as an SPA, which solves your problem. But of course you need to first run "npm run build" to get your build folder, then specify that folder in firebase-cli – kng Jan 21 '18 at 08:31
  • yup I am using firebase-cli to deploy my app. yeah I did specify deploy as an SPA. when I run "npm run build", I only get bundle.js file, there is no build folder. I put all my files i.e index.html, bundle.js in "public" folder. Just to clarify, what files should I have in the build folder? – Seng Wee Jan 21 '18 at 11:51

1 Answers1

2

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.

Seng Wee
  • 534
  • 9
  • 20