Skip to content

How to implement the authentication? #113

Closed

Description

@mztlive

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

Activity

  1. nuric commented on Jul 28, 2022

    @nuric

    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>
  2. locked and limited conversation to collaborators on Nov 21, 2022
  3. converted this issue into a discussion #205 on Nov 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions