Trying to make PrivateRoute, so when I try to access other Pages knowing URL for example, it will navigate me to Login Page because I'm not auth.
My try looks like this:
// ProtectedRoute.js
import React from "react";
import { Route, Navigate } from "react-router-dom";
const ProtectedRoute = ({ element: Element, isAuthenticated, ...rest }) => {
return (
<Route
{...rest}
element={isAuthenticated ? <Element /> : <Navigate to="/" replace={true} />}
/>
);
};
export default ProtectedRoute;
// App.js:
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
axios.get("/api/login").then((response) => {
setIsAuthenticated(response.data.isAuthenticated);
});
}, []);
return (
<Router>
<div className="app">
<Routes>
<Route path="/" element={<LoginWindow />} />
<Route path="/home" element={<HomePage />} />
<ProtectedRoute
path="/protected"
element={<Activitatea/>}
isAuthenticated={isAuthenticated}
/>
And Node.js in back:
app.get("/api/status", (req, res) => {
const pool = new sql.ConnectionPool(config);
pool.connect((err) => {
if (err) {
console.error("Error connecting to the database:", err);
res
.status(500)
.json({ status: "error", message: "Database connection failed." });
} else {
console.log("Connected to the database!");
res.json({
status: "success",
message: "Database connection is established.",
});
}
pool.close();
});
});
The ProtectedRoute component will render the Activitatea component if the user is authenticated, and it will navigate to the home page if not authenticated.