You might run into this typical error while deploying React sites on Netlify that uses React Router for routing. I had spent hours rechecking and refactoring my code, searching for possible errors, when I first came across this error.
Page Not Found: Looks like you've followed a broken link or entered a URL that doesn't exist on this site.
Error message on Netlify
What is the cause of this error?
The problem lies in the way React Router handles routing.
- React Apps are based entirely on a
single root level HTML page
(public/index.html). - React Router allows routing in React apps but at the end of the day, it is still a
single page app
. - React Router works on the client-side (the root level HTML page does not change).
- So, when you visit a route, Netlify (on the server-side) checks for that route in the root (public) folder and throws a
404 - Page Not Found
Error as the route is unavailable.
Example Code with Error:
import React from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Home from './pages/Home';
import Somewhere from './pages/Somewhere';
import PageNotFound from './PageNotFound';
import "./index.css";
const Routes = () => {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/somewhere" exact component={Somewhere} />
<Route component={PageNotFound} />
</Switch>
</BrowserRouter>
);
};
export default Routes;
How to fix this Error?
To fix this error you need to configure redirect rules for your Netlify Site:
- In the root (public) folder, create a plain file named
_redirects
, and add the following line:
/* /index.html 200
Plain _redirect file.
When you assign an
HTTP status code of 200
to a redirect rule, it becomes a rewrite. That means that the URL in the visitor’s address bar remains the same, while Netlify’s servers fetch the new location behind the scenes.
Your site will now deploy successfully on Netlify, and Routing will function correctly without throwing 404 Errors.
Summing Up
Netlify is a cloud service that allows you to host and deploy your React app in minutes. It is a popular choice for most developers.
To learn more about using Netlify with React, click here.
Thanks a lot for reading this far! If you find this article helpful, do give it a like and share. Feel free to ask questions down in the comment section. You may also like,
Resources for this article:
- I found this article helpful - Page Not Found on Netlify with React Router
- From Netlify's Official Documentation - Syntax for the '_redirects' file
- From Netlify's Official Documentation - History pushstate and single-page apps