javascriptreactjsauthenticationreact-routerreact-context

How can I prevent the accessibility of a react component once the user has been logged out of the private route in react?


I have been working on really simple react pages just to clear my concepts. In this, i have a simple authentication method by storing the login info in users.json file (This is just for the sake of simplifying the procedure).

This is the plain and simple code for AuthProvider.jsx

import { createContext, useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import users from "../json/users.json";
const AuthContext = createContext();

const AuthProvider = ({ children }) => {
    const navigate = useNavigate();
    const [user, setUser] = useState(null);

    const login = (email, password) => {
        const foundUser = users.find(
            (u) => u.email === email && u.password === password
        );

        if (foundUser) {
            console.log("creds match");
            setUser(foundUser.email);
            navigate("/dashboard");
            return true;
        } else {
            console.log("creds do not match");
            return false;
        }
    };

    const logout = () => {
        setUser(null);
        navigate("/login");
    };

    return (
        <AuthContext.Provider value={{ user, login, logout }}>
            {children}
        </AuthContext.Provider>
    );
};

export const useAuth = () => {
    return useContext(AuthContext);
};

export default AuthProvider;

I have added a private route in my App.jsx so that only authenticated users can access the dashboard component. Here is the code for PrivateRoute.jsx

import { Outlet } from "react-router-dom";
import { Navigate } from "react-router-dom";
import { useAuth } from "./AuthProvider"

const PrivateRoute = () => {
    const user = useAuth();
    if (!user) return <Navigate to="/login" />
    return <Outlet />
}

export default PrivateRoute;

The problem lies after the logout action. Once I log out, and click on the previous page button in the window, I am redirected to the dashboard which should not happen since I am logged out. Alternatively, if I try to directly enter the "/dashboard" route in the URL, I get redirected to dashboard again.

From what I understand, PrivateRoute is supposed to prevent that sort of thing. Can anyone explain why this is happening? Also, I am aware that I can simply use conditional rendering to check if there is a user and accordingly render the respective component. But PrivateRoute is doing the same thing. So, what is the reason behind this?

Here is the code for my App.jsx component. It contains all the routes.

import { Routes, Route } from "react-router-dom";
import { BrowserRouter } from "react-router-dom";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";
import AuthProvider from "./hooks/AuthProvider";
import Navbar from "./components/Navbar";
import Signup from "./components/Signup";
import Home from "./components/Home";
import PrivateRoute from "./hooks/PrivateRoute";

export default function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <AuthProvider>
          <Navbar />
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/login" element={<Login />} />
            <Route path="/signup" element={<Signup />} />
            <Route element={<PrivateRoute />} >
              <Route path="/dashboard" element={<Dashboard />} />
            </Route>
          </Routes>
        </AuthProvider>
      </BrowserRouter>
    </div>
  );
}

This is the only relevant code. Rest of the components just include home, dashboard, login signup.


Solution

  • The issue is const user = useAuth(); in PrivateRoute. Here user is the entire auth context value, so as a truthy object the Outlet is being rendered instead of the Navigate component to bounce the user to your authentication route.

    You should destructure the user value from the provided auth context:

    const { user } = useAuth();
    

    Full code:

    const PrivateRoute = () => {
      const { user } = useAuth();
    
      return user ? <Outlet /> : <Navigate to="/login" />;
    };