T
TanStack•5mo ago
rare-sapphire

cant throw redirects?

idk if this belongs in router questions but i cant throw redirects at all!! it just shows the errors in the console but without doing anything..
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
export const Route = createFileRoute("/test")({
component: RouteComponent
});

function RouteComponent() {
return (
<div>
<button
onClick={() => {
throw redirect({ href: "/client" });
}}>
Client Redirect
</button>
<button
onClick={async () => {
await serverRedirect();
}}>
ServerFn Redirect
</button>
</div>
);
}

const serverRedirect = createServerFn().handler(async ctx => {
throw redirect({ href: "/server" });
});
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
export const Route = createFileRoute("/test")({
component: RouteComponent
});

function RouteComponent() {
return (
<div>
<button
onClick={() => {
throw redirect({ href: "/client" });
}}>
Client Redirect
</button>
<button
onClick={async () => {
await serverRedirect();
}}>
ServerFn Redirect
</button>
</div>
);
}

const serverRedirect = createServerFn().handler(async ctx => {
throw redirect({ href: "/server" });
});
https://tanstack.com/start/latest/docs/framework/react/server-functions#redirects
No description
5 Replies
generous-apricot
generous-apricot•5mo ago
href in redirect is for external links, use to instead and if you want to redirect client side, use Route.useNavigate() redirect is for server side I think
rare-sapphire
rare-sapphireOP•5mo ago
i was justing href for testing but same thing happens w to and client side it atleast works with usenavigate🙂
generous-apricot
generous-apricot•5mo ago
On the client, redirects are handled by the router automatically from within a route lifecycle or a component that uses the useServerFn hook. If you call a server function from anywhere else, redirects will not be handled automatically. need to use useServerFn I guess
unwilling-turquoise
unwilling-turquoise•5mo ago
throw redirect is not for client. Use useNavigate() hook. If a server function throws redirect then you have to use useServerFn hook
generous-apricot
generous-apricot•5mo ago
it seems that what I said 🙂

Did you find this page helpful?