This is the protected route code:
const ProtectedRoute = (props) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const checkAuth = async () => {
try {
const response = await fetch("http://localhost:3000/checkAuth", {
credentials: "include",
});
const data = await response.json();
if (data.message === "authenticated") {
setIsAuthenticated(true);
} else {
setIsAuthenticated(false);
}
} catch (error) {
setIsAuthenticated(false);
console.error("Error checking authentication:", error);
}
};
checkAuth();
}, []);
return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />;
};
export default ProtectedRoute;
This is the App.jsx code:
function App() {
return (
<>
<Navbar />
<Router>
<Routes>
<Route element={<ProtectedRoute />}>
<Route path="/new" element={<Main />} />
<Route path="/passshow" element={<PassShow />} />
</Route>
<Route path="/" element={<Home />} />
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
</Routes>
</Router>
</>
);
}
export default App;
I am unable to go to "/new"
or "/passhow"
. My backend is properly giving the message as “authenticated”.
I guess there is some problem in my protected route code. So, Can someone please check the code and tell me what i am missing or doing wrong?
Any kind of suggestions will be very grateful.
New contributor
Thor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.