Search code examples
reactjshttp-status-code-404

React 404 when attempting to call a URL only in production


In development I have a React website which makes calls directly to an API hosted on Digital Ocean.

The main url is http://localhost:3000 and loads perfectly well. This contains a series of links all of which redirect to a variation of http://localhost:3000/narrative/[id] such as http://localhost:3000/narrative/4265 or http://localhost:3000/narrative/1.

If I attempt, on development, a reload of http://localhost:3000/narrative/4265 then the page reloads absolutely fine. Similarly, if I open a tab or new browser window and go directly to http://localhost:3000/narrative/4265 the page loads fine.

On production however, I get a 404 both when reloading the page or attempting to navigate to it from a new tab or window.

I've seen the below questions:

  • How to handle 404 in react. I don't think this applies as my instance works fine on development
  • React Router Gives 404 error on production. I'm not too sure how to configure htaccess (if I can put it in the deployable repo or if I have to configure direct on the server), or indeed how to "configure a single entry point" as another answer suggests.

I see from @jonsharpe answer See Building for relative paths that it's possible to use BrowserRouter on my index.js. However I'm not sure that I should be modifying the Route for Link

  <HashRouter>
    <Navigation />
    <Routes>
      <Route path="/" element={<Home />} />
            <Route path="/search" element={<Search />} />
            <Route path="/narrative/:id" element={<Detail />} />
      <Route path="/about" element={<About />} />
      <Route path="/contact" element={<Contact />} />
    </Routes>

  </HashRouter>

Solution

  • Fixed by adding --spm to the pm2 serve build 80 command

    And the suggestion was taken from this answer