React-router
Web Development
JavaScript
Single Page Application
URL Handling

React-router URLs don't work when refreshing or writing manually

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When developing web applications with React, one of the common issues developers encounter involves React Router and the behavior of URLs when refreshing the page or entering URLs manually in the browser. This problem can be particularly baffling for those new to React or client-side routing in general. Below, we delve into why these issues occur and explore solutions to ensure React Router works seamlessly across different scenarios.

Understanding the Problem

React Router is a standard library in React used for handling routing in web applications. It enables the implementation of dynamic routing, which is handled client-side, in contrast to server-side routing used in traditional multi-page applications. The issue with URLs not working when refreshing or manually entering them is fundamentally due to the difference between client-side routing and server-side routing.

In a client-side routed app, the server typically sends the same HTML file no matter the URL requested. The routing to different parts of the application is handled entirely by JavaScript running on the client. This method offers smoother user experiences and faster interactions after the initial page load.

However, this leads to an issue: if a user refreshes the page or enters a URL directly in the browser, the browser makes a request to the server for that URL. But because the server is set up to only respond with the application shell (HTML) and knows nothing about the client-side routes handled by React Router, it can respond with a 404 error if not correctly configured.

Solutions

There are several ways to address this issue, which depends primarily on the server configuration. Below are common solutions depending on the back-end setup:

1. Using BrowserRouter with Server Configuration

Using BrowserRouter in React Router utilizes the HTML5 history API. This requires the server to be configured to handle URLs correctly by returning the application's index.html for every request, leaving the routing to be handled client-side.

Server Configuration Example (Node.js with Express):

javascript
1const express = require('express');
2const path = require('path');
3const app = express();
4
5app.use(express.static(path.join(__dirname, 'build')));
6
7app.get('/*', function (req, res) {
8  res.sendFile(path.join(__dirname, 'build', 'index.html'));
9});
10
11app.listen(9000);

This configuration will direct all requests to your single HTML file, allowing React Router to handle any routing client-side.

2. Using HashRouter

Alternatively, using HashRouter is a straightforward workaround that does not require any server configuration. HashRouter uses the URL hash to keep your UI in sync with the URL. It appends the route paths to the URL using hashes (website.com/#/yourRoute).

Example Usage:

javascript
1import { HashRouter as Router, Route, Switch } from 'react-router-dom';
2
3function App() {
4  return (
5    <Router>
6      <Switch>
7        <Route path="/home" component={Home} />
8        // Other routes...
9      </Switch>
10    </Router>
11  );
12}

Deployment Considerations

When deploying a React app using BrowserRouter, it's important to ensure that your hosting solution can handle HTML5 pushState correctly. Platforms like Netlify or Vercel provide simple configurations to handle client-side routes.

For example, on Netlify, you can add a _redirects file with the following content to ensure all URLs fall back to index.html:

 
/* /index.html 200

Summary Table

ScenarioSolutionConfiguration RequiredConsiderations
Refreshing PageServer route handlingYesServer must redirect all routes to index.html.
Manual URL EntryHTML5 History API or HashRoutingYes for HTML5 History APIHashRouting does not require server-side changes but uses hash in URL.
DeploymentCorrect server handling for SPAYesDeploys to platforms like Netlify or Vercel need a redirects file.

Conclusion

React Router provides powerful tooling for building single page applications (SPAs). Understanding the underlying mechanics of client vs. server-side routing and preparing your server and deployment environments accordingly is paramount to creating a seamless user experience without encountering issues when users refresh the page or enter URLs manually.

In summary, equip your server to properly redirect routes to the React application’s entry point, or use HashRouter for simplicity and avoid server-side hassles, depending on your project's needs and constraints.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.