DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Solving the 404 Error in React + React Router Projects: A Comprehensive Guide

If you've ever encountered a situation in a React Router project where clicking a link transitions smoothly, but hitting the URL directly results in a 404 error, you're not alone. In this article, we will explore how to resolve this issue.

Table of Contents

  1. Overview of the Problem
  2. Understanding the Cause and Solution
  3. Configuring Apache Server
  4. Configuring Nginx Server
  5. Conclusion

Overview of the Problem

We'll begin by describing the phenomenon where clicking a link works as expected, but entering the URL directly leads to a 404 error.

Sample Code

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </div>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

Understanding the Cause and Solution

Next, we'll look at the root cause of this phenomenon and the solution for Apache servers.

Client-Side Routing vs. Server-Side Routing

Since React Router performs routing on the client-side, the server searches for a physical file corresponding to the URL, resulting in a 404 error.

Configuring Apache Server

We'll address this issue by modifying the settings on an Apache server.

Modifying the .htaccess File

Add the following code to your existing .htaccess file:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
Enter fullscreen mode Exit fullscreen mode

Configuring Nginx Server

For Nginx servers, you can set up as follows:

location / {
    try_files $uri $uri/ /index.html;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

If you've ever been plagued by 404 errors with React + React Router, the methods in this article may be your solution. By understanding the behavior of client-side routing and properly configuring your server, you can achieve smooth page transitions.

Top comments (1)

Collapse
 
lfernand_cs profile image
Luis Fernando CS

Thank for allπŸ₯³