Start your developer blog today!
Email me

How to Fix "Page Not Found" error on Netlify while using React Router

Jun 2, 2020 2 min read

Deploying single-page applications (SPAs) in React has never been easier with Netlify.

SPAs are great since they perform all the page routing on the client side, or in the browser. There are no page reloads or extra wait time, making them feel smoother and more natural.

Netlify, acting as our server, expects to be handling routes, but doesn’t know how to handle React Router routes since we never explicitly told Netlify that we’re using React Router.

Example React App

Suppose we had this React code in our App.js file:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const Home = () => <h1>Home!</h1>;
const About = () => <h1>About!</h1>;
const App = () => (
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
      <Route path="/" exact component={Home} />
      <Route path="/about" component={About} />

ReactDOM.render(<App />, document.querySelector("#root"));

The Routing Problem

We have two pages on our site: / and /about.

When we deploy this on Netlify, we’ll be able to access somedomain.netlify.app, which accesses the / route.

From there, we can also navigate using the <nav> element to somedomain.netlify.app/about.

Unfortunately, when we directly enter somedomain.netlify.app/about into our browser’s URL bar, we’ll get the infamous Page Not Found error.

Page Not Found
Looks like you've followed a broken link or entered
a URL that doesn't exist on this site.

The Solution

Netlify supports a _redirects file, which we can add to our root folder to tell Netlify how to handle page routing.

In our case, we can create a file called _redirects in our /public folder with this single line of code:

/*    /index.html   200

That’s it! We’re essentially rerouting everything back to our index.html, where the actual routing will be taking place on the client side.

Be sure to check out Netlify’s documentation on single-page applications as well as their article on redirects.

More JavaScript Articles