Koala7
Koala7

Reputation: 1404

React Routes Problem website only in production

I am working on my personal website and i have found a problem only happening in production, the problem does not happen in my locale environment.

This is the scenario

I have configure the routes like the following

const Routes = () => (
  <Router>
    <Route exact path="/" component={Home} />
    <Route exact path="/works" component={work} />
    <Route exact path="/skills" component={skills} />
  </Router>
)

As i said locally i can access to the all the routes rendering my components work and skills

I build and deploy the code in my domain and i have the problem to access to the following routes

This is the error i get to these routes

This XML file does not appear to have any style information associated with it. The document tree is shown below.

<Error>
  <Code>NoSuchKey</Code>
  <Message>The specified key does not exist.</Message>
</Error>

It is not clear to me what i am doing wrong and why this error is not happening in locale?

Upvotes: 0

Views: 722

Answers (2)

MUGABA
MUGABA

Reputation: 891

  import { HashRouter } from "react-router-dom";
   <HashRouter>
      <App />
   </HashRouter>

Please try that instead

Upvotes: 1

Quentin
Quentin

Reputation: 943510

When you use BrowserRouter you are making use of the History API which lets you write code that says:

Hey browser. I'm going to change the DOM using JavaScript now. It is going to change the page so it is just like the page you would get if you were to visit /example, so you can change the URL in the address bar and make it bookmarkable.

Your problem is that you are making the claim without doing the changes on the server to back that up. When the browser visits the page on the server, it throws an error because you haven't told it what to do for that URL.

You have a few options here:

  • Use HashRouter instead
  • Use a tool like Next.js or Gatsby to generate static pages for deployment to the server
  • Use a tool like Next.js to generate the pages uses server-side rendering (although that isn't an option on S3 which I think you are currently using so you'd need to change hosts too)
  • Use some kind of rewriting configuration so that any 404 error gets converts to a 200 OK error and serves up the skeleton index.html page that bootstraps you app (I really don't recommend this as it breaks normal 404s and is bad for caching).
    • As above but limit it to pages you know exists. This is likely to be a maintenance pain as you need to somehow (probably manually) keep the URLs on the server in sync with changes to your app.

Upvotes: 3

Related Questions