avatarAnge Loron

Summarize

Refresh Woes: Why React Router URLs Break on Page Reload

Why do React-router client-side URLs not work when refreshing or entering manually?

Refresh Woes: Why React Router URLs Break on Page Reload React-router client-side URLs don’t work when refreshing or entering manually. This occurs because React-router handles routing on the client-side after initial page load, but server-side routing is still needed to handle direct URL access. Solutions range from using hash URLs to avoid server-side routing, to full isomorphic/universal rendering where the same JavaScript runs on client and server. The best approach depends on your server technology and SEO needs.

The issue arises because modern client-side routers like React Router work differently than old-school server-side routing. Back in the day, the server would receive a request like http://example.com/about, figure out you wanted the about page, and send back that page. Simple enough.

With React Router, the initial page load still goes to the server, but then the client takes over routing. When you click an ‘About’ link, React Router updates the URL to /about and transitions views on the client-side without hitting the server. Sweet!

But now imagine emailing that /about URL to a friend. When they paste it in, the server gets the request before any client-side JavaScript has loaded. Uh oh, the server doesn’t know what /about means! You get a 404.

So we need server-side routing for direct URLs and client-side routing for in-app navigation. What are our options?

The Hash Hack

With hash URLs like /#/about, the hash part isn’t sent to the server. So the server always returns the root page, client takes over via React Router, and everything works! But hashes are ugly. Pass.

The Catch-All

Set up a server route that returns index.html for any URL. Lets real URLs work but no server rendering. Simple starter option.

The Hybrid

Expand on catch-all by adding some server-side rendering for important routes. More complex but better SEO.

Isomorphic Rendering

Use the same React code on server and client. Initial route rendering happens on server. SEO heaven but requires Node.js.

The best option depends on your stack and needs. For simple sites, catch-all works great. For Node stacks, consider isomorphic rendering. Add server rendering as needed to improve SEO.

Reactjs
React Router
Programming
JavaScript
React
Recommended from ReadMedium