React Router Redirect with Authentication

In our authenticated React applications, we will often need to protect certain routes from unauthorized access. For instance, we may want to protect a dashboard route and only let logged in users access the dashboard.

Let's see how we can protect a route in our React application with React Router 6.

Before we start, the recommendation is to create redirects on the server before a user ever reaches the page.

If you still need to redirect a user on the client side, you can use the <Redirect> component.

Note: The focus of this article is on the redirect. You can bring any type of authentication into your React application. Redirecting based on authentication status is just using an if statement.

React Router 6, comes with the Redirect component that we can use to send a user to a different route.

jsx
import { Redirect } from "react-router-dom";

function Dashboard() {
  return <Redirect to="/login" />
}

If we wanted to only redirect a user if they weren't logged in or didn't have access, we could conditionally return the <Redirect> component.

jsx
import { Redirect } from "react-router-dom";

function Dashboard() {
  const { user } = useAuth0(); // if we were using auth0

  // if there is not user, redirect to the home page
  if (!user) {
    return <Redirect to="/login" />
  }

  // if the user is logged in, return the dashbo
  return (
    <div>
      dashboard goes here
    </div>
  );
}

You can provide a redirect within a Route so that React Router will either return the redirect or a different component of your choice.

jsx
<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>

If you want to replace the current URL instead of adding to your browser's history, you can use the push prop.

jsx
<Redirect push to="/login" />

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)