DEV Community

jkap100
jkap100

Posted on

Redirect with React Router v6

Issue
Building an app that will redirect a user back to the login page if not authenticated.

Solution
We can use Navigate with react router 6 and some simple conditional logic in order to redirect the user back to login when they attempt to view a page and is not authenticated.

Lets assume we have a backend set up that will accept a POST request in order to authenticate a user. Our front end is set up to send a send a POST fetch request and if authenticated store that user in state. The front end fetch could look something like this.

const body = {
  username: username,
  password: password,
};

fetch("/login", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
}).then((r) => {
  if (r.ok) {
    r.json().then((user) => setCurrentUser(user));
    navigate("/home");
  } else {
    r.json().then((err) => setErrors(err.errors));
});
Enter fullscreen mode Exit fullscreen mode

Now we can utilize React Router v6 and Navigate to redirect the the user based on whether or not we have an authenticated user stored in state (currentUser).

Make sure you have installed React Router v6 which can be done with this command :npm install react-router-dom@6.

Next make sure you have imported BrowserRouter, Navigate, Routes, Route from react-router-dom.

import { BrowserRouter, Navigate, Routes, Route } from "react-router-dom"
Enter fullscreen mode Exit fullscreen mode

Once you have your routes set up we can add the following bit of logic to check whether an authenticated user is in state. The following code assumes I have page that shows dogs.

<Route 
  path="/dogs"
  element={
    !currentUser ? <Navigate to="/login" /> : <DogsShow />
/>
Enter fullscreen mode Exit fullscreen mode

In english this asking if not currentUser then navigate to /login else render DogsShow.

And there you have it a quick and easy way to add redirect logic to your app.

Top comments (0)