solid-router
solid-router copied to clipboard
How to implement the authentication?
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
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>