Categories
React Answers

How to fix React-router URLs don’t work when refreshing or writing manually?

Spread the love

When React Router URLs don’t work after refreshing or manually typing them in, it’s usually because the server doesn’t recognize them as valid routes and returns a 404 error.

This happens because React Router works on the client-side and doesn’t directly communicate with the server for route handling.

Here are steps we can take to fix this issue:

Use HashRouter

Instead of BrowserRouter, you can use HashRouter. HashRouter uses the hash portion of the URL (i.e., everything after the #) to maintain application state, which doesn’t require server configuration.

import { HashRouter as Router } from 'react-router-dom';

<Router>
  {/* Your routes */}
</Router>

Configure Server for Client-Side Routing

If we want to stick with BrowserRouter, we need to configure your server to serve the same index.html file for all routes. This allows React Router to handle routing on the client side.

For example, in Express.js, you can achieve this with the following:

const express = require('express');
const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(3000);

This code serves the index.html file for all routes, letting React Router handle the routing.

Configure Server-Side Rendering (SSR)

If you’re using server-side rendering with React (like Next.js), the server should be configured to handle routing correctly. Ensure that your server code properly renders the React application for each route requested.

Check your PublicPath Configuration

If we’re using Webpack or any other bundler, ensure that the publicPath configuration is correctly set in your webpack configuration file.

output: {
  publicPath: '/',
}

Ensure Base URL is Set Correctly

In your index.html file, make sure the base URL is set correctly.

<base href="/" />

Avoid Absolute URLs in Links

Make sure you’re using relative URLs when linking between routes within your application. Absolute URLs may cause unexpected behavior.

Test in Different Environments

Make sure to test your application in different environments to ensure routing works as expected.

By following these steps, you should be able to fix the issue of React Router URLs not working when refreshing or typing them manually.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *