Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v6.14.0: Getting 404 on refresh & writing manually URL (using createBrowserRouter)

I'm using routes with createBrowserRouter and everything is fine locally but when I upload my website build and make my site live, when I enter the url manually or refresh the page, I'm getting 404 Error, I've researched on various stack questions but didn't get the answer on how exactly solve this issue when you're using createBrowserRouter instead of <Routes> //Routes here </Routes>.

I also tried spa-github-pages where you make 404.html file in /public and copy the script mentioned in the github repo, but this solution also didn't work.

I'm using a simple method of routing with latest react-router version. I know its a client side routing issue but how to solve it exactly with react-router v6.14.0

Also another problem is when I get 404 Not Found error I can't see my <404NotPage /> well designed component page.

Here is my code:-

App.js

import { createBrowserRouter, RouterProvider } from "react-router-dom";

const router = createBrowserRouter([ 
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "about-us",
    element: <About />,
  },
  {
    path: "*",
    element: <NotFound />, // also can't see this page
  },
])

export default function App() {
  return <RouterProvider router={router} />;
}
like image 713
Reacting Avatar asked Dec 06 '25 07:12

Reacting


2 Answers

Add .htaccess file and add below code if you are hosting your build on Apache server (cpanel)

<IfModule mod_rewrite.c> 
  RewriteEngine On  
  RewriteBase /  RewriteRule ^index\.html$ - [L]  
  RewriteCond %{REQUEST_FILENAME} !-f  
  RewriteCond %{REQUEST_FILENAME} !-d  
  RewriteCond %{REQUEST_FILENAME} !-l  
  RewriteRule . /index.html [L]
</IfModule>
like image 68
Reacting Avatar answered Dec 08 '25 19:12

Reacting


I had the same issue, this worked for me:

  {
    path: "/*",
    element: <NotFound />
  }
like image 42
Maroun Avatar answered Dec 08 '25 21:12

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!