Search code examples
reactjsreact-routernetlify

React router No Match 404 not working when deployed?


I added a No Match 404 error page to my website, and it works fine when I go to the wrong path on localhost, but after I deploy and go to an invalid path like .../invalidpath I get the default netlify page not found error. Below is my App.js component:

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Navigation from './components/navigation/Navigation';
import Home from './pages/home/Home';
import Projects from './pages/projects/Projects';
import Contact from './pages/contact/Contact';
import NoMatch from './pages/404page/404Page';

import './App.scss';

function App() {
  return (
    <div className='app'>
      <Navigation />
      <Switch>
        <Route exact path='/' component={Home} />
        <Route path='/projects' component={Projects} />
        <Route path='/contact' component={Contact} />
        <Route path='*' component={NoMatch} />
      </Switch>
    </div>
  );
}

export default App;

Solution

  • If you've built the app with create-react-app and you're deploying to Netlify, you need to add a _redirects file inside the public directory of your project in order to support client side routing (React Router). It should have this inside:

    /*  /index.html  200
    

    Details here. Also, check the official docs from Netlify regarding for Redirects and rewrites