I'm currently developing a Web application with authentication and I'd like to know what to do as a private route. Is it a good way to make a condition in my useEffect of one of my pages that I want private to know if the token is present or not?
ex:
import {useEffect} from "react";
import {useNavigate} from "react-router-dom";
function Dashboard() {
const token = localStorage.getItem("token")
const navigate = useNavigate()
useEffect(() => {
if (!token) {
navigate("/login")
} else {
fetchAPI ........
}
}, []);
return (
)
}
export default Dashboard
If your goal is to log the user out regardless of where he is then I suggest using the <outlet/>
component.
import {useEffect} from "react";
import {useNavigate} from "react-router-dom";
import { Outlet } from "react-router-dom";
function ProtectedRoute() {
const token = localStorage.getItem("token")
const navigate = useNavigate()
useEffect(() => {
if (!token) {
navigate("/login")
} else {
fetchAPI ........
}
}, []);
return (
<Outlet/>
)
}
export default ProtectedRoute
Wherever your routes are being handled you'd essentially wrap the children inside of this <ProtectedRoute/>
component. It would look something like this :
<Route element={<ProtectedRoute/>}>
<Route path="/dashboard" element = {<Dashboard/>}
</Route>
By doing so you're essentially lessening the amount of code you're writing to do the same check. Every single time you navigate to a different page, this useEffect will get triggered. Naturally you can also start implementing the useContext
and createContext
hooks as to not have an insane amount of prop drilling going on. Another big help is that you can use the ProtectedRoute
component as a layout component. If you have sidebar
or navbar
or whatever that needs to be displayed on every page, this is a great way as well. Hope this helps!