Troubleshooting 404 error when page refreshed.

Mayur K SettyMayur K Setty
2 min read

The Issue

Ever hit that dreaded 404 Not Found error after deploying your React project? You’ve got everything perfect, your project builds flawlessly, and you’re ready to go live! The deployment is a breeze, and the homepage looks stunning. But as soon as you click through the navbar to another page and reload, BAM! A 404 error crashes your party! After all that effort, there happens to be a bug, yet again that has to be fixed!

Turns out it's not a bug that is appearing due to an error made by you! It's something way more fundamental. Let me break it down for you:

Development

  • You run the project using the vite development server and localhost intercepts all route requests.

  • When for eg. you visit route '/about' , dev server simply serves the in-memory app and not through the OS file system.

  • All requests are internally routed back to index.html

  • React Router handles the route and loads to the correct component

Production

  • react builds a static bundle (HTML, CSS & JS)

  • routing still makes use of History API but the server has no clue.

  • when refreshed browser sends http request to eg. route '/about' expecting a about.html and since it doesn't exist -> 404 page is displayed.

  • react never loads because index.html was never served

Solution

So it happens so that there is actually a pretty straightforward fix for this... All we need to do is redirect back to index.html when an unmatched route is detected and not the 404 page.

Here are the fixes on some popular deployment platforms Vercel and Netlify that I have personally tested on.

Vercel

Create a vercel.json file in the root directory of your React project and this piece of code:

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

Netlify

add _redirects file in public/ , and add the code:

/* /index.html 200

and voila! Your unexpected refresh behaviour is terminated!

0
Subscribe to my newsletter

Read articles from Mayur K Setty directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mayur K Setty
Mayur K Setty

Student at RV University x Kalvium (BCA in Software Product Engineering) | MERN Stack Dev {} | Wildlife Enthusiast | Photographer | Runner | Guitarist