Search code examples
javascriptreactjsdeploymentviteproduction-environment

How to resolve 404 error in a deployed react- vite app?


I have a production-ready React app built with vite. I have run the build process and uploaded the contents of the dist file within the subdirectory it is supposed to be in. When i visit the URL it throws a 404 error in the console. Failed to load resource: the server responded with a status of 404 (Not Found) - index-77febc61.js:1 for my index.js file. I have checked the index.html file to ensure the src tag is pointing to the right js file and it seems fine.

The URL to the site should be https://mydomainname.com/susbcriber. All the files are uploaded in the subscriber directory but on visiting the site it shows a white screen with the 404 error.

Any help on how i could resolve this is greatly appreciated.


Solution

  • To resolve a 404 error in a deployed React-Vite app, you should check the following areas:

    1. Base URL Configuration: Ensure that you have set the correct base URL for your Vite app in your vite.config.js file. In your case, the base URL should be set to "/subscriber". Here's how you can configure it:
    // vite.config.js
    
    export default {
      base: '/subscriber/',
    }
    
    1. Build Again: If you've made changes to your configuration or code, it's a good practice to rebuild your app before deploying it to ensure that the latest changes are included in the build.
    npm run build
    
    1. Deployment Directory Structure: Make sure that all the contents of the dist directory are correctly uploaded to the /subscriber directory on your server. Double-check the file names and paths to ensure they match the structure in your dist directory.

    2. Server Configuration: If you're using a server (e.g., Nginx or Apache) to serve your React-Vite app, ensure that it is correctly configured to handle the base URL. In the case of Nginx, your configuration might look like this:

    location /subscriber {
      alias /path/to/your/app/dist;
      try_files $uri $uri/ /subscriber/index.html;
    }
    

    This configuration tells Nginx to serve files from the dist directory when the URL starts with /subscriber. It also routes all requests to index.html to ensure client-side routing works.

    This configuration tells Nginx to serve files from the dist directory when the URL starts with /subscriber. It also routes all requests to index.html to ensure client-side routing works.

    1. Hashed File Names: If you are using hashed file names (e.g., index-77febc61.js), ensure that the names in your index.html file match the actual file names in the dist directory. The hash may change with each build, so it's important to keep them in sync.