How to implement Auth0 protected route in react-router v6?

Share this Content

If you are building a react application with Auth0 for user management, then you may also face the problem of implementing the Auth0 protected route. I’ve also faced the same problem, and in this blog, I’ll show you how I implemented the Auth0 protected route in react-router v6. Implementing the ProtectedRoute in version 5 was pretty easy. The sample codes are also available on multiple websites. In the newest version, it is easier, but you may not find that much sample code on the internet.

Because react-router v6 is a bit different with some upgrades you may find results on ProtectedRoute, but all of them could not be working properly in your project.

You can check the Auth0 official guide for protecting your route. Although it is very much applicable for version 5 but not applicable for the newest version.

Changes in React- Router v6:

React-router is a popular routing library for React applications. The library provides a set of core components and functions for managing application routing. The latest version of React-router is v6.

React.js logo

The biggest change in react-router v6 is the introduction of a new bigger Router component. The Router component is the heart of the react-router library and is responsible for managing the application’s routing. The new Router component is a significant upgrade from the previous version and provides a number of benefits.

The most notable change is the way in which the Router component renders its children. In previous versions of react-router, the Router component would render its children in a static manner. This meant that the order in which the children were rendered would always be the same.

However, in react-router v6, the Router component renders its children in a dynamic manner. This means that the order in which the children are rendered can be changed at runtime. This is a significant change that allows for more flexibility when it comes to routing.

Another big change in react-router v6 is the way in which routes are defined. In previous versions of react-router, routes were defined using a static object. This object would be passed to the Router component and used to render the children.

However, in react-router v6, routes are defined using a dynamic function. This function is responsible for returning a route object that is used by the Router component to render the children. This is a more powerful and flexible way to define routes.

The last major change in react-router v6 is the way in which the router handles errors. In previous versions of react-router, errors were handled by the Router component itself.

However, in react-router v6, errors are handled by a new component called ErrorBoundary. This component is responsible for catching errors that occur during the execution of the application and displaying an error message to the user.

Overall, the changes in react-router v6 are significant and provide a number of benefits. The new Router component is more powerful and flexible. The way in which routes are defined is more powerful and flexible. And the way in which errors are handled is more robust.


Now, let’s come to the point. How you can protect your route using Auth0.

Implementing Auth0 protected route:

Before implementing all these processes first check what version you’re using. I’m using version 6.4.3, the latest one.

To implement Auth0 protected route, we’ll be needed 3 files.

  1. App.js :
    We’ll be implementing the Protect method here.
  2. PrivateRoute.js (or whatever you name this):
    This page is needed to implement the actual logic behind the protection.
  3. history.js:
    This page will simply store the browser history.

Now, we’ll simply start with the simplest one.

History.js:

We’ll write two lines of code here.

Subscribe to Tech Break
import { createBrowserHistory } from "history";
export default createBrowserHistory();

What is createBrowserHistory?

It is a function that creates a history object that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the default history object for React Router. It is a singleton, so it is shared across all components that import it.

Our first step is done. Now, we’ve to write the logic.

PrivateRoute.js:

In this file, we’ll be creating a simple logic.

If the user is logged-in, let the user access the private routes, else redirect the user to the login/signup page.

Now, this logic can be written in two ways. One is by using user object, and another is by using isAuthenticated object. Both will work completely fine. I’ll be showing both of them.

By user object:

The user object in Auth0 stores the information like username, password, and email of the logged-in user. If the user is not logged in then it will be null.

Now, the if-function will check if the user object is null or not. If it is null, then it will go to the else part, i.e. the user will be navigated to loginWithRedirect, where the user will be redirected to the login page.

import { Outlet, Navigate} from "react-router-dom";
import React from "react";
import { useAuth0 } from "@auth0/auth0-react";

const PrivateRoute = () => {
    const { user, loginWithRedirect } = useAuth0();
    if (user) {
        return <Outlet />;
    } else {
        return <Navigate to={loginWithRedirect()} />;
    }
};

export default PrivateRoute;

Now, we can write the same code with a small change.

By using isAuthenticated :

Now, isAuthenticated is a boolean value that returns true and false. If the user is logged in then it will return true, else it will return false.

The code will be just the same as the previous one. We’ll just exchange user with isAuthenticated.

import { Outlet, Navigate} from "react-router-dom";
import React from "react";
import { useAuth0 } from "@auth0/auth0-react";

const PrivateRoute = () => {
    const { isAuthenticated, loginWithRedirect } = useAuth0();
    if (isAuthenticated) {
        return <Outlet />;
    } else {
        return <Navigate to={loginWithRedirect()} />;
    }
};

export default PrivateRoute;

Now, we’ll go to the final step, i.e. adding the PrivateRoute inside Routes.

App.js:

import "./App.css";
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./Components/Pages/Home";
import About from "./Components/Pages/About";
import Nav from "./Components/Nav";
import Footer from "./Components/Footer";
import Contact from "./Components/Contact";
import Dashboard from "./Components/Pages/Profile";
import PrivateRoute from "./Components/PrivateRoute";
import history from "./utils/history";
import { useAuth0 } from "@auth0/auth0-react";

function App() {
  return (
    <div className="App">
      <Router history={history}>
        <Nav />
        <Routes>
          <Route path="/" exact element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="/blog" element={<Posts />} />
          <Route element={<PrivateRoute/>}>
            <Route path="/dashboard" element={<Profile/>} />
              {/* Other Routes you want to protect */}
          </Route>
        </Routes>
        <Footer />
      </Router>
    </div>
  );
}

export default App;

Okay, so we’ve successfully protected the route “Profile“. Now check your react application if it is working fine or not.

If still it is not working, then do the changes in the index.js file.

index.js:

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { Auth0Provider } from "@auth0/auth0-react";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <Auth0Provider
    domain="YOUR_DOMAIN_KEY"
    clientId="YOUR_CLIENT_ID"
    redirectUri={window.location.origin}
  >
    <App />
  </Auth0Provider>
  );

After doing these changes, your react application will be working properly and also your routes will be successfully protected.

After applying Auth0 protected route, see how the route works for the “Profile” page. You can only access the page if you’re logged in, else you’ll be redirected to the login page.


If you still got any problems, feel free to ask me in the comment section. And also you can visit the official GitHub repository for Auth0-react-samples. Try to understand what they’ve done there and implement the changes to your application.

Share this Content
Snehasish Konger
Snehasish Konger

Snehasish Konger is the founder of Scientyfic World. Besides that, he is doing blogging for the past 4 years and has written 400+ blogs on several platforms. He is also a front-end developer and a sketch artist.

Articles: 191

Newsletter Updates

Join our email-newsletter to get more insights