How does the location of functions affect SPA behaviour ? #5679
-
|
I'm working on a project with better-auth and tanstack start and I'm trying to implement protected routes. If I put getUser serverFn into the same file that I define better-auth 'auth' constant my project kind of disables spa behaviour and just refreshes on every navigation. So, when we have this code: // auth.ts
export const auth = betterAuth({
...
});
import { createServerFn } from "@tanstack/react-start";
import { authMiddleware } from "./auth-middleware";
// I'm calling this in beforeLoad of /login route
export const getUser = createServerFn({ method: "GET" })
.middleware([authMiddleware])
.handler((ctx) => {
return ctx.context.user;
});video2.mp4But if I move my getUser function to another file it just gets fixed. // auth.ts
export const auth = betterAuth({
...
});
// I moved getUser into auth-middleware.tsvideo3.mp4This is where and how I use getUser if it's relevant: import { Logo } from "@/components/logo";
import { getUser } from "@/lib/auth-middleware"; // This is the only thing that changes
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/_auth")({
component: RouteComponent,
beforeLoad: async () => {
const user = await getUser();
if (user) throw redirect({ to: "/oyla" });
},
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
probably leaking server code into client and thus not hydrating. if you are importing a server function from a file that also exports server-only things (here I assume a solution can be to wrap the server-only things into a function with |
Beta Was this translation helpful? Give feedback.
probably leaking server code into client and thus not hydrating.
if you are importing a server function from a file that also exports server-only things (here I assume
export const auth = betterAuth(). will be server-only, then this export cannot be elided by our compiler and thus will fail on the client.a solution can be to wrap the server-only things into a function with
createServerOnlyFn