Private routes in React Router

March 15, 2021

Problem: You have some content on your web app you don’t want to show unless the user if signed in.

Solution: Private routes in React router.

We’ve covered React router earlier, so now we’ll just discuss the mechanisms of Private routing.

A simple React router:

Adding a private route:

<Switch>
        <PrivateLoginRoute
          authed={token === null}
          exact
          path="/login"
          component={LoginRouter}
        />

<PrivateRoute
          authed={token !== null}
          exact
          path="/today"
          component={TodayRouter}
        />
</Switch>

And define Private route as a component:

function PrivateRoute({ component: Component, authed, ...rest }) {
    let pathname = rest.location.pathname.split("/");
    pathname = pathname[pathname.length - 1].toLowerCase();
    if (pathname === "today") {
      setSelectedList(null);
      setHeaderTitle("Today");
    } else if (pathname === "settings") {
      setSelectedList(null);
      setHeaderTitle("Settings");
    } else {
      var temp = lists.lists.filter((e) => e._id == pathname)[0];
      if (temp) {
        setSelectedList(temp);
        setHeaderTitle(temp.title);
      }
    }
    return (
      <Route
        {...rest}
        render={(props) =>
          authed === true ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{ pathname: "/login", state: { from: props.location } }}
            />
          )
        }
      />
    );
  }
  function PrivateLoginRoute({ component: Component, authed, ...rest }) {
    return (
      <Route
        {...rest}
        render={(props) =>
          authed === true ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{ pathname: "/today", state: { from: props.location } }}
            />
          )
        }
      />
    );
  }

Written by Gagandeep Rangi who likes to talk about himself in third person. Twitter Instagram