React-router urls don’t work on browser refresh or entered manually

If your react router urls don’t work on browser refresh or when entered manually, then it means you have not configured paths on your server. Simply point all the urls to the index.html file using .htaccess, like this –

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

Why it happened?

Okay so here is the reason why react router urls could work while navigating within the website but not directly loading from browser –

The routes in react-router-dom are virtual. They don’t exist as directory or page on server. They are just different components loaded for different navigation.

Suppose, you are on the home page – https://akashmittal.com. Server will always point at index.html for it and if you try to reload or manually enter in browser then it will always point to this file. But, for react, no other page exists on server. So, if you are trying to open https://akashmittal.com/reactjs then there will be route not found error.

This is because /reactjs is neither a permalink or directory on server. We have defined this route on react-router-dom. So, only react app can understand this. And to understand, react need to load itself first. But since nothing got back from server so react never get loaded and hence we got the error.

The solution is simple – Send all the routes or permalink to the index.html file. This way server will load the reactjs app and then react will decide which component to show according to the route in browser address bar.

Note: Do not send CSS, JS, Images urls to the index.html file