How to fix React/Vite redirect issue in Vercel

ยท

2 min read

If you're experiencing redirect issues when deploying your React application with React Router on Vercel, there are a few common solutions you can try:

  1. Create a _redirects file: Vercel supports a redirect configuration file called _redirects. In your project's root directory, create a file named _redirects (without any file extension) and add the following line to it:

     /*    /index.html   200
    

    This rule tells Vercel to redirect any request to the index.html file, which is the entry point of your React application.

  2. Configure a rewrite rule in vercel.json: Vercel allows you to define custom routing rules using a vercel.json configuration file. Create a vercel.json file in your project's root directory (if it doesn't exist already) and add the following content:

     {
       "rewrites": [
         {
           "source": "/(.*)",
           "destination": "/index.html"
         }
       ]
     }
    

    This configuration tells Vercel to rewrite any request to the index.html file.

  3. Use the BrowserRouter with a basename prop: In your React application's entry file (e.g., index.js), where you mount your app, you can specify a basename prop for the BrowserRouter component. For example:

     import React from 'react';
     import ReactDOM from 'react-dom';
     import { BrowserRouter } from 'react-router-dom';
     import App from './App';
    
     ReactDOM.render(
       <BrowserRouter basename={process.env.PUBLIC_URL}>
         <App />
       </BrowserRouter>,
       document.getElementById('root')
     );
    

    The basename prop ensures that React Router uses the correct base URL when generating the routes.

  4. Verify your routes: Double-check your route configurations in your React Router setup. Ensure that you have defined the correct paths, components, and any necessary nested routes.

After applying any of these solutions, rebuild your React application (npm run build) and redeploy it to Vercel. The redirect issue should be resolved, and your application's routing should work as expected.

ย