-
-
Notifications
You must be signed in to change notification settings - Fork 914
Performance is horrible when using recommended Authentication patterns #3997
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
atleast for supabase currently im determining if someone is authenticated or not by using supabase getSession. im making sure im using the browser client on the browser and the serverClient on the server so there are no round trips required to atleast determine if a user has session cookies. that is in _root then in _authed, if there is session cookies i make a call to then ofcourse every request to supabase is happening server side and using the session cookies and if row level security is set correctly then this is safe. So, cookies are always fetched locally and allow for instant navigation ✅ It is ofcourse possible for someone to manually set anyKind of session cookies and that will allow them to navigate to a _authed page, but then the first call to supabase.auth.getUser() will throw as they dont have the correct JWT and they will be redirected back to /signin or wherever the trick is this isomorphic fn to use the supabase/ssr browserClient or serverClient depending on the runtime context.
this method is based off of the supabase/ssr auth for sveltkit docs : https://supabase.com/docs/guides/auth/server-side/sveltekit I assume this method of checking cookies either from the browser or from the server depending on the runtime context, fetching userData once and caching it, and then ensuring that you validate the JWT on serverside actions should work for any auth system and allow for instant navigation. just need to make sure that whatever api setup youre using you pass and validate your JWT for every data retrieval request and make sure you dont rely on simple userID params for accessing userdata but rather actually determine user access from the decoded JWT. supabase does this under the hood with getUser() and also with row level security. |
Was facing the same issues, wanted to share my similar solution as @Mikephii stated, but a little more complete, just to have something to talk about if this is the way to go? For context, using:
Heavy caching seems nessesary to provide the "instant" client navigation feel. Using // src/routes/_root.tsx
export interface RouterContext {
queryClient: QueryClient
trpc: TRPCOptionsProxy<AppRouter>
session: null
}
export const Route = createRootRouteWithContext<RouterContext>()({}) // src/functions.ts
import { getWebRequest } from "@tanstack/react-start/server"
import type { RouterContext } from "~/routes/__root"
export const $getSession =
createIsomorphicFn()
.client(async (queryClient: RouterContext["queryClient"]) => {
const { data: session } = await queryClient.ensureQueryData({
queryFn: () => authClient.getSession(),
queryKey: ["auth", "getSession"],
staleTime: 60_000, // cache for 1 minute
revalidateIfStale: true, // fetch in background when stale
})
return {
session,
}
})
.server(async (_: RouterContext["queryClient"]) => {
const request = getWebRequest()
if (!request?.headers) {
return { session: null }
}
const session = await auth.api.getSession({
headers: request.headers,
})
return {
session,
}
}) better-auth's // src/routes/_authed/route.tsx
import { $getSession } from "~/functions"
export const Route = createFileRoute("/_authed")({
component: RouteComponent,
beforeLoad: async ({ location, context, preload }) => {
if (preload) {
return
}
const { session } = await $getSession(context.queryClient)
if (!session) {
throw redirect({
to: "/login",
search: {
redirect: location.href,
},
})
}
return {
session,
}
},
}) Consume the session: // src/routes/_authed/private-route/index.tsx
const { session } = Route.useRouteContext() |
I've been running into a few similar surprises mostly related to the Observations:
What I ideally would like to achieve is a way to prevent rapid-firing of edit: fwiw, I'm currently using a export const Route = createFileRoute('/_authed')({
component: RouteComponent,
context: ({ context: { authClient } }) => ({
queryOptions: {
session: queryOptions({
staleTime: 1000 * 15,
queryKey: queryKeys.core.session(),
queryFn: async () => {
const isAuthenticated = await authClient.isAuthenticated();
return {
isAuthenticated,
sessionUser: isAuthenticated ? await getSessionUserData(authClient) : null
};
}
})
}
}),
loader: async ({ context: { queryClient, queryOptions } }) => {
// We're using `fetchQuery` because `ensureQueryData` would ignore the
// staleTime and never refresh the query, while we want to periodically
// recheck the session so we can send the user to login if necessary.
const session = await queryClient.fetchQuery(queryOptions.session);
if (!session.isAuthenticated) {
// Redirect login here
}
}
});
function RouteComponent() {
const { queryOptions } = Route.useRouteContext();
const queryResult = useSuspenseQuery(queryOptions.session);
if (queryResult.data.isAuthenticated) {
return (
<SessionUserContext value={queryResult.data.sessionUser}>
<Outlet />
</SessionUserContext>
);
}
return null;
} |
Which project does this relate to?
Router
Describe the bug
When using the recommended patterns for authentication, particularily in tanstack start, the performance of the app is garbage.
because onBefore load for _root or _authed routes runs on every page navigation, even when you are clientside, it necessitates a sever round trip before being able to navigate resulting in incredibly unresponsive apps. (even if the auth service was processing in 1ms the server trip is usally about 200 -300 ms for most people)
With tanstack router there were some solutions to this by storing the authstate in a react context or hook outside of the inner app and so the state would persist as normal across transitions without a server trip and you could refresh you session tokens as normal when needed.
With tanstack start this is no longer an option as it does not appear as if its possible to have a global state that is persisted across route transitions, (ie client side behaviour that we love, that makes the apps fast).
This is quite obviously not in line with the promise of tanstack start from their very own landing page:
There should be some VERY clear documentation on how to avoid this performance issue, and patterns and practices on how to achieve client first performance.
Your Example Website or App
https://github.com/tanstack/router/tree/main/examples/react/start-clerk-basic
Steps to Reproduce the Bug or Issue
use any of the authenticated template starters and attempt to navigate
Expected behavior
should be an option to have state stored locally and persisted across page navigation, particularily for auth. if that already is an option then there should be docs showing how to use this to avoid the repeated server trips to re-authenticate on every link
Screenshots or Videos
No response
Platform
Additional context
No response
The text was updated successfully, but these errors were encountered: