Same route for private and protected content

Hi, Is there a way to have a single route show different content depending on the user being logged in or not? I came up with this, but I'm pretty sure it's incorrect:
export default function PublicLayout(props: RouteSectionProps) {
const user = createAsync(() => getUser());
const location = useLocation();

return (
<MetaProvider>
<Switch
fallback={
{/* Public content */}
<Suspense>{props.children}</Suspense>
}
>
<Match when={location.pathname === '/' && !user()}>
{/* Public home page */}
<Suspense><HeroPage /></Suspense>
</Match>
<Match when={location.pathname === '/' && user()}>
{/* Protected home page */}
<Suspense><Home /></Suspense>
</Match>
</Switch>
</MetaProvider>
);
}
export default function PublicLayout(props: RouteSectionProps) {
const user = createAsync(() => getUser());
const location = useLocation();

return (
<MetaProvider>
<Switch
fallback={
{/* Public content */}
<Suspense>{props.children}</Suspense>
}
>
<Match when={location.pathname === '/' && !user()}>
{/* Public home page */}
<Suspense><HeroPage /></Suspense>
</Match>
<Match when={location.pathname === '/' && user()}>
{/* Protected home page */}
<Suspense><Home /></Suspense>
</Match>
</Switch>
</MetaProvider>
);
}
Any hints welcome!
9 Replies
brenelz
brenelz3d ago
Could you just check if user doesn't exist then redirect somewhere
indigo.snowboll
indigo.snowbollOP3d ago
In this case I want to show the public home page. Eg. try accessing github logged out vs logged in. You get 2 different pages, on the same exact path ("/").
brenelz
brenelz3d ago
You could have the index route and use Show when=user
indigo.snowboll
indigo.snowbollOP3d ago
I'm doing that with the Switch/Match.
brenelz
brenelz3d ago
Like do you need that logic in the layout?
indigo.snowboll
indigo.snowbollOP3d ago
Not necessarily. I just want the functionality.
brenelz
brenelz3d ago
I guess this would work
indigo.snowboll
indigo.snowbollOP3d ago
Using FileRoutes, the common advice for dealing with user sessions is on the layout, so, that's why I'm putting it there. It doesn't work. I have another layout that is only for protected access, and the router gets very confused on which content to show. I'm also getting Hydration Mismatch errors left and right, but that can be something else. I'm seeing some inconsistencies in the examples, eg. using createResource or createAsync for the same things. I got it to work. Seems like changing that last/stray createResource to createAsync fxed it. Thanks for jumping in, @brenelz !
brenelz
brenelz3d ago
Oh that's great

Did you find this page helpful?