DevOps | Cloud | Analytics | Open Source | Programming





How To Fix – Error URLs Doesnt Work After Refresh in React-Router ?



In this post, we will explore How To Fix – Error URLs Doesn’t Work After Refresh in React-Router. Error Log-


cannot GET \*url\*


cannot GET /URL' error


Cannot GET /dashboard


404 not found


Cannot GET /settings

  Many a times, this is not quite a react\react-router problem. Instead it is more of a webserver config problem or misuse of  relative script in the index.html file. Try the below options to handle this issue. In this fix, what you would do is -

  • Redirect all of your server requests to /index.html.
  • Any request - made to the server will now respond with index page.
  • And would then fetch any Javascript resources that is required.
  • Subsequently React Router will handle from that point and would serve the subsequent view.
  To achieve this approach, we have to modify the server configs, depending on what server we use. So follow follow the below server Specific guides to achieve this.  

Solution Apache Server:

  • If you are using Apache as the web server, you have to modify the .htaccess file.
(The .htaccess file allow users to configure directories of the web server they control - without modifying the main configuration file)

  • Usually .htaccess file is at the root of your website or the root of your project.
  • This approach will work also for next.js static export also.
  • Ensure that that the path after RewriteBase & RewriteRule shows the folder where the app is (e.g. any sort of subfolder etc.) . This is especially crucial in case you have sub-domain etc.

<IfModule mod\_rewrite.c>
  RewriteEngine On    <--- THIS MUST BE FIRST LINE
  RewriteBase /
  RewriteRule ^index\\.html$ - \[L\]
  RewriteCond %{REQUEST\_FILENAME} !-f
  RewriteCond %{REQUEST\_FILENAME} !-d
  RewriteCond %{REQUEST\_FILENAME} !-l
  RewriteRule . /index.html \[L\]
</IfModule>

  • If .htaccess fix doesn't work, then try to modify the httpd.conf . (Apache HTTP Server is configured by placing directives in plain text configuration files. The main configuration file is usually called httpd. conf).
  • The Apache HTTP Server configuration file is in /etc/httpd/conf/httpd.conf OR /etc/httpd/conf. And is mostly self-explanatory.
  • Change AllowOverride None to AllowOverride All in httpd.conf <Directory /var/www/>
 

Solution Nginx Server :

If you are using Nginx server, you could try to modify the config.conf file for you. By default, the configuration file is named nginx.conf . It is generally placed in the directory /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx. Below is suggested by facebook for react - https://create-react-app.dev/docs/deployment/#serving-apps-with-client-side-routing


location / {
  if (!-e $request\_filename){
    rewrite ^(.\*)$ /index.html break;
  }
}

 

Solution Express :

Make the below changes if you are using Express.


app.get('/\*', function(req, res) {
 res.sendFile(path.join(\_\_dirname, '<YOUR\_COMPLETE\_index.html\_FILE\_PATH>'), function(err) {
 if (err) {
 res.status(500).send(err)
 }
 })
})

OR


expressApp.get('/\*', (request, response) => {
        response.sendFile(path.join(\_\_dirname, '<YOUR\_COMPLETE\_index.html\_FILE\_PATH>'));
});

 

Solution Webpack :

If you are using Webpack-dev-server and facing this issue, this is for you.

  • You could try configuring WebPack server. Webpack-dev-server can be used to quickly develop an application. Webpack-dev-server is Webpack's officially supported CLI-based tool to start a static server for your code. Webpack-dev-server gives you a single command that starts a static server with built-in live reload.
  • Add the historyApiFallback: true in the config.
publicPath specifies the base path for all assets in an application.

historyAPIFallback will redirect any 404 to /index.html.


devServer: {
  publicPath: '/',
 historyApiFallback: true,
}, 

 

Solution Managed Server\Hosting:

If you are using a Managed Server or Hosting service, use below -

  • Create a "/_redirects" file in the public folder with the below contents

/\* /index.html 200

  • This will Re-direct every requests to .index.html.
 

Solution Firebase:

If you are using Firebase, add the below to your firebase.json file in the root of your app (in the hosting section). Using rewrite will show the same content for multiple URLs. Rewrites are very useful with pattern matching - since you can accept any url that matches the pattern. And let the client-side code decide what to show.


{
  "hosting": {
   // ...

  // Serves index.html for requests to files or directories that do not exist
     "rewrites": \[{
       "source":"\*\*",
       "destination": "/index.html"
     }\]
  }
}

The rewrites attribute contains an array of rewrite rules, where each rule must include the fields in the table below.

Field

Description

rewrites

source (recommended) or regex

URL pattern - which if matched to the initial request URL, triggers Hosting to apply the rewrite

  • Use source to specify a glob (recommended).
  • Use regex to specify a RE2 regular expression.
destination

A local file that must exist This URL can be a relative or an absolute path.

  Hope this helps to solve the issue.  

Other Interesting Reads -

    react-refresh not working ,react router v6 refresh 404 ,react url not working on refresh ,react-router urls don't work when refreshing ,url changes but doesn't load component react ,url changes but doesn't load component ,react router cannot get /url on refresh ,react-router-dom refresh problem ,react router browser refresh ,how to avoid 404 error when reload a page in react? ,react router 404 on refresh ,react router express cannot get ,failed to load resource: the server responded with a status of 404 (not found react-router) ,cannot get url react router dom ,React-router URLs don't work when refreshing or writing manually ,cannot GET *url* ,cannot GET /URL' error ,Cannot GET /dashboard ,404 not found ,Cannot GET /settings ,URL Doesn't Work After Refresh in React-Router ,How to avoid 404 error when reload a page in react? ,React-router v4 - cannot GET *url* ,On page refresh getting "404 not found" error in react js ,'cannot GET /URL' error on refresh with React Router ,Reload the page gets 404 error using React Router ,React-router URLs don't work when refreshing or writing manually