Handling 404 Errors on Vercel Deployments: A Step-by-Step Guide with React, Vite, and react-router-dom

The 404 Error Issue

This error occurs when a user tries to access a specific route directly or refreshes the page. In traditional server-rendered applications, the server handles route requests and serves the corresponding HTML pages. But in SPAs, routing is managed on the client-side, and the server may not be aware of these client-side routes. This discrepancy results in the server returning a “Page Not Found” error for direct route accesses, causing frustration for users and confusion for developers.

Using Vercel Rewrites

Vercel, our preferred deployment platform, provides a solution to this problem through its powerful “rewrites” functionality. Rewrites allow us to configure how incoming requests to our application’s URLs should be handled. With the right rewrite rules, we can ensure that all requests are redirected to the root URL, preventing the 404 error from occurring.

Procedures :

  1. Create a vercel.json File:

To define our rewrite rules, we need to create a vercel.json file in the root directory of our project. This file serves as the configuration for our Vercel deployment.

// vercel.json

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

In the above code, we defined a simple rewrite rule:

  • "source": "/(.*)": This source pattern matches any URL, capturing all incoming requests.

  • "destination": "/": It specifies that regardless of the incoming URL, it should be rewritten to the root URL (/).

credit to this article

Did you find this article valuable?

Support Mandeep Singh by becoming a sponsor. Any amount is appreciated!