how to implement protected routes with FileRoutes?

For example, allow /xyz only if store.user.isAuthenticated
1 Reply
Madaxen86
Madaxen862w ago
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>

)
}
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. Using deferStream prevents sending content before the query has fully resolved. Show prevents any child from firing queries to avoid errors. (Note that this creates a waterfall intentionally in this case.) Login and logout actions need to revalidate refreshSession

Did you find this page helpful?