How to Fix Vercel 404 error: Child URL Path Issues

David Bilson - Oct 11 '23 - - Dev Community

Vercel is a popular hosting platform for front-end applications, offering various deployment and hosting features. Deploying a React app to Vercel is a straightforward process, but it can become problematic when you need to handle redirects from child paths to the root.
When deploying a React app, you might encounter a situation where your child paths aren't automatically redirected to the root, causing unexpected behavior in your application. After having the page deployed, for example, https://yourwebsite.vercel.app, this path loads successfully, right? But once you navigate to a different route on the page and try to refresh, you'll usually see a 404 error like the one below.

Vercel 404 error

There are cases whereby you would want to show someone a specific page on your react app, and you would want to give them the exact URL to that page, for example, https://yourwebsite.vercel.app/contact-page. If the person loads the page, they will get a 404 error simply because Vercel fails to load the child path from the root.

I assume you already have your app built and deployed on Vercel? If you haven't, please do so. Let's say you already have a React app with multiple routes, and your app is hosted on Vercel. When you visit a child path of your app, such as https://yourapp.vercel.app/child, you might expect it to redirect to the root path (https://yourapp.vercel.app/), but it doesn't happen by default. This can lead to issues like broken links, incorrect rendering, and a poor user experience.

To solve this problem, you can use Vercel's "rewrites" feature. "rewrites" allows you to configure how requests are handled, including URL redirection. In this case, you want to redirect all child paths to the root path.

Create a vercel.json file within the root folder of your project.

create vercel.json file

Then paste the code below within the json file:

{
  "rewrites": [
    { "source": "/(.*)", "destination": "/" }
  ]
}
Enter fullscreen mode Exit fullscreen mode

"rewrites" specifies the rules for URL rewrites.
{ "source": "/(.*)", "destination": "/" } tells Vercel that for any URL path that matches /(.*) (essentially any path), redirect the request to the root path (/).
Ensure you push these new changes to update your repository.

By adding this simple configuration in the vercel.json file, you can resolve this issue. With this configuration in place, your React app will redirect child paths to the root path, ensuring that all your routes work as intended.

. . . . . . . . .
Terabox Video Player