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]

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 – 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 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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

How to use React?

This article will help you to know how to use React JS in web applications. React js creates static websites with optimized performance and speed. Step 1: Install create-react-app npm…
View Post