-2

I am using ReactJs with react-router-dom for my website. The developer build on my localhost works great. localhost:3000/register takes me to the registration page. But in the build version created with npm run build, the myIp/register page takes me to a file not found page, but not the one I added in the App.js. The home path works when I enter my ip as url. App.js:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './css/Style.css';
import './css/Register.css';
import Home from './pages/Home';
import NotFound from './pages/NotFound';
import Register from './pages/Register';

function App() {
  return (
    <Router>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/register' element={<Register />} />
        <Route path='*' element={<NotFound />} />
      </Routes>
    </Router>
  );
}

export default App;

My package.json: (with the version information)

{
  "name": "my_page",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.2",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Has someone an idea how to fix that?

2
  • 2
    Generally, apache, nginx, such web servers are required for route settings. Commented Oct 15, 2022 at 10:02
  • 1
    You have to configure your server to redirect 404 to index.html Commented Oct 15, 2022 at 11:24

1 Answer 1

0

Thanks for the hint with the server config. So I was able to find a working solution: https://stackoverflow.com/a/59630881/12411687

Simply place the following .htaccess file in the root

<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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.