solid-router icon indicating copy to clipboard operation
solid-router copied to clipboard

How to implement the authentication?

Open mztlive opened this issue 2 years ago • 1 comments

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

mztlive avatar May 16 '22 13:05 mztlive

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>

nuric avatar Jul 28 '22 10:07 nuric