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
There’s a Navigate component
https://docs.solidjs.com/solid-router/reference/components/navigate#navigate
And the useNavigate hook:
https://docs.solidjs.com/solid-router/reference/primitives/use-navigate
Both work isomorphic.
does useNavigate work server side (and behave like redirect())
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
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)
Well then you should use a server function that checks if the user is authenticated and then returns or throws the redirect if not.
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 typeYou can also render the Navigate component conditionally like
So as soon as that Navigate component is rendered it will navigate? (and if isLoggedIn() is initially true it won't navigate)
Yes.
Give it a try. With the above setup the children will not render.
Ok that sounds good, thanks so much :)