Recently a friend was having a super weird bug with their React app. Whenever you would interact with a link, instead of being routed to the correct client-side component, the screen is replaced with raw JSON.
However, if you use your browser's refresh button after this, it suddenly renders correctly. Like so:
They were pulling their hair trying to figure this out!
What's going on?
Well, it turns out it has to due with the way browsers handle http requests from the URL.
When you visit a URL that happens to be exactly the same as your API route. When that happens, your browser makes a GET request back to the server for that route, so you just get whatever your server sends.
Your server routes and your React Router routes SHOULD NOT conflict. How can we fix this?
Well, it's pretty simple--
You really have three options here:
Use a hash router
This is a that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL. It's the difference between
Because of this URL hash, it puts no limitations on supported browsers or web server. Server-side routing is independent from client-side routing, which prevent just rendering JSON.
Redirect all HTTP requests to root,
meaning /, /something and /anything will serve /. Then host your API on another subdomain, like api.mydomain.com
Choose a route to serve your API from
This can be something like mydomain.com/api. Forward all requests from any route EXCEPT /api and it's subroutes to the root.
Personally, I would go with option 3 as I believe it's cleanest. Just forward all requests except if it's an API request. Super simple.
I hope this helps anyone who is having trouble with their browser rendering JSON instead of their React component! This was a weird thing I have never encountered before so I thought I would share it with the world!
Thanks so much for reading! Have a great day and HAPPY CODING!