Davis
Davis2mo ago

I'm encountering an issue where, after

I'm encountering an issue where, after logging in with Google, the currentUser query (which relies on getAuthUserId) consistently returns null on the first dashboard load. I've verified the login is successful. However, a page reload resolves the issue. Could this be a bug related to the initial authentication state?
// dashboard
const user = await context.queryClient.fetchQuery({
...convexQuery(api.users.currentUser, {}),
staleTime: 0,
gcTime: 0,
})
console.log("auth route", user)
if (!user) {
throw redirect({ to: "/sign-in" });
}

// convex/users.ts
import { getAuthUserId } from "@convex-dev/auth/server";
import { query } from "./_generated/server";

export const currentUser = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (userId === null) {
return null;
}
return await ctx.db.get(userId);
},
});
// dashboard
const user = await context.queryClient.fetchQuery({
...convexQuery(api.users.currentUser, {}),
staleTime: 0,
gcTime: 0,
})
console.log("auth route", user)
if (!user) {
throw redirect({ to: "/sign-in" });
}

// convex/users.ts
import { getAuthUserId } from "@convex-dev/auth/server";
import { query } from "./_generated/server";

export const currentUser = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (userId === null) {
return null;
}
return await ctx.db.get(userId);
},
});
4 Replies
erquhart
erquhart2mo ago
Have you tried the bit I shared in the link above (https://github.com/erquhart/convex-saas/blob/6bb6c561d1430f7b5c2c393b23c4000a6229faec/src/routes/_app.tsx) Using ensureQueryData() to get an initial response before loading the page
Davis
DavisOP2mo ago
Same. ensureQueryData or fetchQuery doesn't fix my issue. I mean the first time the user data always will get null. After that i reload the browser then get the user data
erquhart
erquhart2mo ago
I would consider this the canonical TanStack Start / Convex implementation (has auth too, albeit via Clerk): https://github.com/get-convex/templates/tree/main/template-tanstack-start-clerk looking to see how auth is handled there gah, it uses dummy data, no authorization But it does have an _authed parent directory A few approaches here: https://github.com/get-convex/templates/blob/7b74f039b3358eb25b296461814a7f179b4bfe87/template-tanstack-start-clerk/app/routes/convexposts.tsx#L25-L30 It looks like even the server rendered bit is just rendering undefined until auth loads, this may be the approach to take for now - make your pages expect a potentially undefined auth
Davis
DavisOP2mo ago
ok let me take a look and thank you for your response

Did you find this page helpful?