Home > Blockchain >  ReactJS: Getting 404 when a /about page is opened
ReactJS: Getting 404 when a /about page is opened

Time:11-02

This is the first time I'm deploying a React Web App to the firebase hosting. In my index.html file I only have the root div:

<body>
    <div id="root" class="container"></div>
</body>

That's all there is in the body. Then I have an index.js in the src folder in which I have:

import { BrowserRouter as Router, Route } from "react-router-dom";'
import HomeScreen from "./screens/HomeScreen";
import AboutScreen from "./screens/AboutScreen";
...
ReactDOM.render(
    <Router>
        <div>
            <Route exact path="/" component={HomeScreen} />
            <Route exact path="/about" component={AboutScreen} />
        </div>
    </Router>,
    document.getElementById("root"))

Then to open the about page I have linked it as:

import { Container, Nav, Navbar } from 'react-bootstrap';
...
<Nav.Link href="/about">About</Nav.Link>

When I do npm run build and then firebase deploy it deploys and I can see the changes on the home page. But when I click on about it gives me 404

404 error picture

I have the folder named build which is the public folder and after the build, it only has index.html and 404.html and a static/js folder that has some generated js and txt.

So, I'm not sure why I'm getting 404. In dev build i.e. localhost the navigation works fine.

CodePudding user response:

That is because it is a static deployment of a single index.html, about.html does not exist, you can only access to the index.html, and the other views "doesn't" because is a single-page-application, but you can redirect all URL other than "/" to the index.html file, editing the firebase.json

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

CodePudding user response:

For single page applications, redirect rules must be specified. Every routes should be redirected from index.html file

You need to specify the deployment directory being deployed and the redirect rules

This is my react app being deployed to firebase hosting alongside firebase functions

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  }
}
  • Related