skip to Main Content

I have created a website using React and Vite (as a bundler). On my local host everything’s working fine, but on production my routes are not working, and it’s showing me 404 errors.

Every time I have to open my homepage only then after clicking on navbar tabs I can change my page and then routes are working. What am I doing wrong?

2

Answers


  1. Your description suggests that your webserver is not correctly set up to handle routing for a single-page application (SPA). In a typical SPA, the frontend routing logic requires that the initial HTML file (usually index.html) containing your React application is served in response to all route requests. This setup is essential because it allows the React code to handle routing dynamically based on the URL present in the browser.

    If you’re developing a simple SPA with React, you’ll want to ensure that your webserver consistently delivers the index.html file, which includes your bundled React application, for every requested route. This configuration allows your React app to interpret the URL and render the appropriate components without the need for additional requests to the server for each new route.

    As an example, for an nginx server, you can achieve this by modifying your server configuration to direct all traffic to the index.html file:

    location / {
        root /var/www/html;
        try_files $uri $uri/ /index.html;
    }
    

    This configuration tells nginx to attempt to serve the requested URL or directory ($uri $uri/), and if it fails (i.e., the resource does not exist), it falls back to serving the /index.html file. This setup ensures that your React app is loaded and can then handle the routing as defined in your frontend code.

    Login or Signup to reply.
  2. Try using HashRouter,
    In your react project find the page where routes are configured, mostly main.jsx
    replace BrowserRouter with HashRouter

    import { HashRouter as Router } from "react-router-dom";
    

    Rebuild your project!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search