#how to implement protected routes with FileRoutes?

4 messages · Page 1 of 1 (latest)

stable raven
#

For example, allow /xyz only if store.user.isAuthenticated

hearty lance
#

I tend to create a layout and place all routes in that layout
You can create layouts without adding to the route like
/(auth) as a directory to place all protected files
And as a sibling (not child) create (auth).tsx

#

const AuthLayout: ParentComponent = (props) => {
  const isAuthenticated = createAsync(() => refreshSession(), {
    deferStream: true,
  });

  onMount(() => {
    function refreshWhenVisible() {
      if (!document.hidden && isAuthenticated()) {
        revalidate(refreshSession.key);
      }
    }
    document.addEventListener("visibilitychange", refreshWhenVisible);

    //refresh the token every ~ 5 minutes 
    const interval = setInterval(refreshWhenVisible, 1000 * 60 * 5);

    onCleanup(() => {
      document.removeEventListener("visibilitychange", refreshWhenVisible);
      clearInterval(interval);
    });
  });

 return (

  <Suspense>
        <Show
          when={isAuthenticated()}
          fallback={
            <Navigate href={"/login?redirectTo:" + location.pathname} />

          }
        >{props.children}</Show>
      </Suspense>

)
}

#

The refreshSession returns false when it fails and will lead to render the navigate component which redirects the user to the login page.
In on mount there’s the interval the refreshes the session. Cancels the interval when the users leaves the tab/window and restarts when coming back.