How to do client side redirects

Quick client vs SSR question: What is the recommended way to do a redirect from the client side? My understanding is throw redirect() is only available from an SSR context. Also, if I wanted to redirect regardless of whether I was client of server side, would "use_server" along with throw redirect() be appropriate there. If not what would the recommended way to do this be.
10 Replies
icanflyit
icanflyitOP5mo ago
does useNavigate work server side (and behave like redirect())
Madaxen86
Madaxen865mo ago
Well redirect is supposed to be used in server functions and server actions (and api routes) While useNavigate and Navigate are supposed to be used inside components
icanflyit
icanflyitOP5mo ago
This is for an authentication guard (against an external server), since I have SSR the goal is that the authentication request is made from ssr and if it fails, it's redirected and the client never receives the page But there are times when the authentication will be done client side (like after logging in)
Madaxen86
Madaxen865mo ago
Well then you should use a server function that checks if the user is authenticated and then returns or throws the redirect if not.
icanflyit
icanflyitOP5mo ago
So with a server function, will the client make a request to the solid start server (and all that code for the request is automated) and then the solid start server will make the request to the backend? Also a more general js/ts question, with useNavigate, can I throw navigate() (returns void) if I don't want execution to continue? Or does an error have to be of an actual error type
Madaxen86
Madaxen865mo ago
You can also render the Navigate component conditionally like
<Show when={isLoggedIn()}
fallback={<Navigate href="/login" />}>
{props.children}
</Show>
<Show when={isLoggedIn()}
fallback={<Navigate href="/login" />}>
{props.children}
</Show>
icanflyit
icanflyitOP5mo ago
So as soon as that Navigate component is rendered it will navigate? (and if isLoggedIn() is initially true it won't navigate)
Madaxen86
Madaxen865mo ago
Yes. Give it a try. With the above setup the children will not render.
icanflyit
icanflyitOP5mo ago
Ok that sounds good, thanks so much :)
Want results from more Discord servers?
Add your server