Fixing SPA routing 404 on refresh issue in Firebase

Milos Bejda
2 min readOct 14, 2017

--

With the advent of new Firebase features, a 404 page after page refresh is not something your visitors or users should experience anymore.

This 404 after refresh issue commonly occurs in single page application when the HTML 5 push state routing strategy is used to hide the hashbang(!#) or hash(#) at the root of the url path. Both, the hashbang (!#) and hash(#) are well known staples in single page application routing. Despite them being an important routing item that prevents the server from rendering a file path, they are commonly viewed as unattractive and unwanted.

There are steps you can take to hide them but there are tradeoffs. For starters, you can leverage the HTML 5 push state I mentioned earlier. But, if a visitor refreshes their page they will get an unwelcoming and confusing 404 page instead of the page they refreshed.

A different approach requires you to have access to the hosting server. If you have access to the server you can SSH into it and add a mod rewrite to the web server configuration file. But, you have to be ok with going out of your way to figure out what modifications need to be done to make the url rewrite work correctly.

With the Firebase rewrite url feature you can get rid of those url staples without using HTML 5 push state or configuring a web server. Assuming you have a Firebase application, open up the Firebase config file and add the following rewrite configuration to the hosting section.

“rewrites”: [{
“source”: “**”,
“destination”: “/index.html”
}]

Deploy your application and boom! Now if your visitors refresh on any route, instead of seeing a displeasing 404 page, they will see the same page they refreshed.

--

--

Responses (7)