1

i need help to protect routes in my reactjs project , i want that only a loged user can access to Home Page, and only not loged user can access to the signin and signup forms

import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import SignInForm from "./pages/SignInForm";
import SignUpForm from "./pages/SignUpForm";
import Wallet from "./components/Wallet";
import Welcome from "./pages/Welcome";
import Home from "./pages/Home";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Welcome></Welcome>}></Route>
        <Route path="/signin" element={<Navbar></Navbar>}>
          <Route index element={<SignInForm></SignInForm>}></Route>
        </Route>
        <Route path="/signup" element={<Navbar></Navbar>}>
          <Route index element={<SignUpForm></SignUpForm>}></Route>
        </Route>
        <Route path="/wallet" element={<Navbar></Navbar>}>
          <Route index element={<Wallet></Wallet>}></Route>
        </Route>
        <Route path="/home" element={<Navbar></Navbar>}>
          <Route index element={<Home></Home>}></Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;
user206904
  • 504
  • 4
  • 16
  • Does this answer your question? [Conditional Routes in react router dom v6](https://stackoverflow.com/questions/70912894/conditional-routes-in-react-router-dom-v6) – exaucae Feb 06 '22 at 16:55

3 Answers3

2

This is how I did it, basically, you wrap the route and check if the user is authenticated, if he's not, redirect back to where he should be. This uses react-router v6, you can find more information about it in the authentication section of the official docs. They have a very good example on stackblitz, you should take a look at that.

import { useIsAuthenticated } from "your-auth-package"
import { Navigate, useLocation } from "react-router";

const AuthenticatedRoute = ({ children }) => {
  const isAuthenticated = useIsAuthenticated();
  const location = useLocation();

  // not logged in
  if (!isAuthenticated) {
    console.log("not authenticated");
    return <Navigate to="/" state={{ from: location }} replace />;
  }

  return children;
};
<BrowserRouter>
  <Routes>
    <Route
      path="/dashboard"
      element={
        <AuthenticatedRoute>
          <Dashboard />
        </AuthenticatedRoute>
      }
    />
  </Routes>
</BrowserRouter>
picklepick
  • 1,370
  • 1
  • 11
  • 24
1

Here's an example with a simple helper function that doesn't require any separate component:

import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';

function App() {
  
  const user = ... // get user from context/redux/request...etc.
  const auth = (element) => (!user ? <Navigate to={'/log-in'} /> : element);

  return (
    <BrowserRouter>
      <Routes>
        <Route element={<Welcome />} path='/' />
        <Route element={<SignInForm />} path='/log-in' />
        <Route element={<SignUpForm />} path='/sign-up' />
        <Route element={auth(<Home />)} path='/account' />
      </Routes>
    </BrowserRouter>
  );
}

In this example, Home is an "auth" route -- requires a user and redirects to LogIn without a user. Welcome, SignInForm, and SignUpForm can be accessed without a user.

Zachary Duvall
  • 304
  • 1
  • 9
0

Make a component like below and adjust it to your requirement.


import React from "react";
import { Redirect, Route } from "react-router-dom";
import auth from "../services/authService";

function ProtectedRoute({ path, component: Component, render, ...rest }) {
  return (
    <Route
      {...rest}
      render={(props) => {
        if (!auth.getCurrentUser())
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: props.location },
              }}
            />
          );
        return Component ? <Component {...props} /> : render(props);
      }}
    />
  );
}

export default ProtectedRoute;

then wrap the route like this

  <ProtectedRoute path="/wallet" element={<Navbar></Navbar>}/>

Arsene Wenger
  • 587
  • 4
  • 21