T
TanStack17mo ago
correct-apricot

Display different content depending on whether one is authenticated or not

Hey there! 👋 I've used https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes and file-based routing with great success in a React app with a straightforward directory and file structure:
routes
- _authed
- settings
- feed
- home
routes
- _authed
- settings
- feed
- home
I am now building an app where--ideally--I would like to have mysite.com/foo render differently based on whether one is authenticated or not. My first thought was that I might be able to solve it like this:
- _authed
- foo
- foo
- _authed
- foo
- foo
But according to https://tanstack.com/router/latest/docs/framework/react/guide/route-matching this would always match _authed/foo first and never try foo. Have you solved this (or a similar) problem? How did you solve it? Thanks for your help. 🙏
1 Reply
absent-sapphire
absent-sapphire17mo ago
You are running into an issue here, since you are effectively trying to create two routes that both get called when you go to /foo. This is definitely a problem. You could achieve this by checking the auth status and render different views accordingly.
export const Route = createFileRoute('/foo')({
beforeLoad: ({ context: { auth } }) => {
return { viewType: auth.isAuthenticated ? 'authed': 'public' }
},
component: function() {
const viewType = Route.useRouteContext({ select: s => s.viewType })

if (viewType === 'authed') {
return <AuthedFooView />
}

return <PublicFooView />
}
})
export const Route = createFileRoute('/foo')({
beforeLoad: ({ context: { auth } }) => {
return { viewType: auth.isAuthenticated ? 'authed': 'public' }
},
component: function() {
const viewType = Route.useRouteContext({ select: s => s.viewType })

if (viewType === 'authed') {
return <AuthedFooView />
}

return <PublicFooView />
}
})
But this definitely does feel clunky and doesn't allow you to really utilize the other features like search params and etc.

Did you find this page helpful?