Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React PWA: create-react-app using react-router renders 404 page

This happens ONLY when I add my PWA to the home screen and run the app from there. I'm not seeing this behavior when I run the app on the mobile or desktop browser.

I'm working on a React app built using create-react-app. It works fine after running npm run build and serving it using any local http-server. It also seems to work fine once I deploy it to Firebase or now and open the site on Firefox or Chrome mobile browsers. However, when I hit the "Add to Homescreen" button on the pop-up, it get's added, but opening it from the homescreen icon renders the 404 route.

I used react-router's <Switch/> component to route to a custom 404 page if no path matches the URL. Here's how I defined my Router "configuration":

<Router>
    <Switch>
      <Route exact path="/" component={Login} />
      <Route path="/login" component={Login} />
      <Route path="/sign-up" component={SignUp} />
      <Route 
        render={() => (
        <div>
          <h1>Error 404: Not Found</h1>
          <Link to="/">Go Home</Link>
        </div>)}
      />
    </Switch>
</Router>

Versions of packages in my package.json:

  • react: ^16.2.0
  • react-scripts: 1.1.0
  • react-router-dom: ^4.2.2
like image 739
glocore Avatar asked Dec 05 '22 12:12

glocore


1 Answers

The reason for this is that when the app is opened from the homescreen, it looks for the ./index.html route mentioned in the manifest.json file that is created by create-react-app. This path does not match any of the routes in the router configuration, and so it renders the 404 page. If no 404 page were created, then a blank page would be displayed, since all routes would return null.

You can observe the same behavior if you visit the URL manually on your browser at: https://website.com/index.html. The app will either render a blank page or a 404 page (if you've created one).

In order to fix this, change the start_url field in the manifest.json file as follows:

{
  ...
  start_url: "/"
}

Now when the app is started from the homescreen, it will look for the '/' path instead of '/index.html'.

like image 146
glocore Avatar answered Dec 08 '22 02:12

glocore