Points of Caution for React react-router-dom

Tech Knowledge
Published on November 15, 2024

Important Notes

By using react-router-dom, you can implement URL-based routing.
However, the behavior differs between the development environment (Vite) and the production environment.

In the production environment, if you click a link (e.g., https://hoge.com/test) with the mouse using a Link tag, routing will occur correctly. However, if you directly enter the same URL (https://hoge.com/test) into the browser's address bar, a 404 Not Found error will occur.
This is because when a URL is entered directly, the web server tries to find a file named "/test". Since the file "/test" does not exist, a 404 Not Found error results.
On the other hand, when a link is clicked with the mouse, React (JavaScript) rewrites the screen and simultaneously rewrites the browser's URL (no request to the server occurs at this time). Therefore, a 404 error does not occur.

Solution

Redirect to the entry point if a 404 occurs.
This is the proposed solution.

If you are using Azure Static Web Apps, create a staticwebapp.config.json file directly under the public folder.

All requests that result in a 404 should be redirected to the entry point (typically index.html).

// staticwebapp.config.json

{
  "navigationFallback": {
    "rewrite": "/index.html"
  }
}

※ The reason 404 errors do not occur in the development environment (Vite) is probably because Vite performs a similar redirection.