S
SolidJS11mo ago
aryzing

How to handle auth with solid-router?

Given an app where users have access to additional routes when they are logged in, how to set up the router so that it, - redirect users to "home" if they are logged in and happen to navigate to the login or signup page? - redirect users to login page when visiting a route that requires authentication but they are not logged in? Is the following a good starting point? Where would the redirects be inserted?
export function App() {
return (
<Router root={Providers}>
{/* Logged out routes */}
<Route component={UnauthenticatedApp}>
<Route path="/sign-up" component={SignUp} />
<Route path="/log-in" component={LogIn} />
</Route>

{/* Logged in routes */}
<Route component={AuthenticatedApp}>
<Route path="/" component={Home} />
<Route path="/profile" component={Profile} />
</Route>
</Router>
);
}
export function App() {
return (
<Router root={Providers}>
{/* Logged out routes */}
<Route component={UnauthenticatedApp}>
<Route path="/sign-up" component={SignUp} />
<Route path="/log-in" component={LogIn} />
</Route>

{/* Logged in routes */}
<Route component={AuthenticatedApp}>
<Route path="/" component={Home} />
<Route path="/profile" component={Profile} />
</Route>
</Router>
);
}
6 Replies
Brendonovich
Brendonovich11mo ago
That’s pretty much what I’d do
aryzing
aryzingOP11mo ago
What would the code inside AuthentcatedApp look like?
Brendonovich
Brendonovich11mo ago
For my app it gets the current user in a cache, which redirects if there is no user
aryzing
aryzingOP11mo ago
Taking the example above, if AuthenticatedApp redirects the user, but the user is not in any of its child routes, doesn't it always attempt to redirect when it mounts if there's no user?
Brendonovich
Brendonovich11mo ago
Yeah that’s kinda the point - I want all routes underneath the authenticated section to be inaccessible unless there’s a user If there’s a route that doesn’t require a user but will function differently if there is one then I take it out of the wrapper
aryzing
aryzingOP11mo ago
I see. Maybe a bit of a corner case, but say AuthenticatedApp redirects to /log-in when the user is not logged in, and say the user visits /sign-up. Won't AuthenticatedApp "override" the url the user entered into the browser and take them to /log-in? How do you handle that? I believe I misunderstood how the router works. Turns out only the components for the matched routes are actually run, so it's fine to have redirects in both routes Thanks for the help!
Want results from more Discord servers?
Add your server