React router guard

Viewed 63

I'm new to react JS and learning react router. I recently got stuck on what I'm doing. What I'm trying to do is a route should not be accessible when user is not or is authenticated.

  • When not authenticated user should only be able to access /home and /login
  • When authenticated they can only access /profile, /settings and not be able to access the other routes either using browser back button or change browser URL.

What is happening is I'm still able to access all the routes even if I change isAuthenticated returned value.

I'm using React 18.2.0 and React Router 6.

Below are my codes

Main.tsx

import { Routes, Route } from 'react-router-dom'
import HomePage from '@modules/home/views'
import LoginPage from '@modules/login/views'
import ProfilePage from '@modules/profile/views'
import SettingsPage from '@modules/Settings/views'
import { PublicRoutes, ProtectedRoutes } from 'src/middleware/AppRoutes'

const AppMain = () => {
  return (
    <main>
      <Routes>
        <Route element={<ProtectedRoutes />}>
          <Route path="/profile" element={<ProfilePage />} />
          <Route path="/settings" element={<SettingsPage />} />
        </Route>
        
        <Route element={<PublicRoutes />}>
          <Route path="/" element={<HomePage />} />
          <Route path="/login" element={<LoginPage />} />
        </Route>
      </Routes>
    </main>
  )
}

export default AppMain

RouteGuard.tsx

import { Navigate, Outlet, useLocation } from 'react-router-dom'

export const isAuthenticated = () => {
  return false
}

export const PublicRoutes = () => {
  const location = useLocation()

  return !isAuthenticated()
    ? <Outlet />
    : <Navigate to='/login' state={{ from: location }} replace />
}

export const ProtectedRoutes = () => {
  const location = useLocation()

  return isAuthenticated()
    ? <Navigate to='/profile' state={{ from: location }} replace />
    : <Outlet />
}
1 Answers

You've mixed up the auth condition and the ternary.

If the user is authenticated and accessing a protected route you should render the Outlet, otherwise render the redirect to "/login".

If the user is authenticated and accessing a public route you should render the redirect to "/profile", otherwise render the Outlet.

Example:

const PublicRoutes = () => {
  const location = useLocation();

  return isAuthenticated() ? (
    <Navigate to="/profile" state={{ from: location }} replace />
  ) : (
    <Outlet />
  );
};

const ProtectedRoutes = () => {
  const location = useLocation();

  return isAuthenticated() ? (
    <Outlet />
  ) : (
    <Navigate to="/login" state={{ from: location }} replace />
  );
};

Edit react-router-guard

Related