Replies: 1 comment
-
I'm not sure if this is the best way to do it but I use a nested route that acts as a user guard: /* Assuming useUser is a signal indicating whether the user is logged in or not */
const UserGuard: Component = () => {
const navigate = useNavigate();
/* Authentication guard */
createEffect(() => {
/* Here null means user is not logged in. It could also be undefined
which means we don't know yet.*/
if (useUser() === null) {
navigate("/login", { replace: true });
}
});
return (
<Show when={useUser()} fallback="Loading user...">
<Outlet />
</Show>
);
} It displays loading user if the user signal is undefined and redirects if it is null (as in the user is not logged in). If they are logged in then it shows the child routes that are guarded. I then use it in the Routes: <Routes>
<Route path="/private" element={<UserGuard />}>
<Route path="/profile" element={/* ... */} />
</Route>
</Routes> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have some pages that need to be logged in before they can be used, but I don't know how to encapsulate this component to achieve the purpose
Beta Was this translation helpful? Give feedback.
All reactions