DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How React Router can cause unexplained behavior with your browser
professorjrod
professorjrod

Posted on

How React Router can cause unexplained behavior with your browser

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.

raw JSON

However, if you use your browser's refresh button after this, it suddenly renders correctly. Like so:

success

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.

react router

React Router isn't actually "routing" anywhere from a HTTP sense -- it's just rendering different JavaScript/HTML and storing its "location" in 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:

1.
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 website.com/api and website.com/#/api

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.

2.
Redirect all HTTP requests to root,

meaning /, /something and /anything will serve /. Then host your API on another subdomain, like api.mydomain.com

3.
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!

Top comments (0)

New programmer and javascript

Stop by this week's meme thread!