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?
6 Replies
That’s pretty much what I’d do
What would the code inside
AuthentcatedApp
look like?For my app it gets the current user in a
cache
, which redirects if there is no userTaking 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?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
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!