Elfinslayer
Elfinslayer14mo ago

getUserIdentity() returning null

Hey all, I'm building an app and I've come across an issue where I have a currentUser function that uses the standard ctx.auth.getUserIdentity() method, but it seems to be returning null despite being logged in. I'm successfully using the function in another function with no issues. This is called as a query on the frontend. Code:
export const currentUser = query({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();

console.log(identity);

const user = await ctx.db
.query("users")
.withIndex("by_token", (q) =>
q.eq("tokenIdentifier", identity?.tokenIdentifier ?? "")
)
.unique();

if (!user) throw new Error("Invalid current user");

return user;
},
});
export const currentUser = query({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();

console.log(identity);

const user = await ctx.db
.query("users")
.withIndex("by_token", (q) =>
q.eq("tokenIdentifier", identity?.tokenIdentifier ?? "")
)
.unique();

if (!user) throw new Error("Invalid current user");

return user;
},
});
console.log there to confirm it's null.
No description
6 Replies
erquhart
erquhart14mo ago
Welcome! I haven't run into this, but I can try and help troubleshoot. Have you tried calling this query from the same place you're calling the other query?
Elfinslayer
ElfinslayerOP14mo ago
I've changed how I was pulling in the data. the identity doesn't seem to be initially loaded (which makes sense in hindsight). For others that have this question, the solution was to account for that in the frontend by handling a null user and showing a loading overlay until it's all there.
jamwt
jamwt14mo ago
@Elfinslayer one note is some folks find the skip capability of useQuery useful here: https://docs.convex.dev/client/react#skipping-queries
Convex React | Convex Developer Hub
Convex React is the client library enabling your React application to interact
jamwt
jamwt14mo ago
that way you can do something like:
const {isSignedIn} = useAuth();
const myMessages = useQuery(api.messages.list, isSignedIn ? {...params} : "skip");
const {isSignedIn} = useAuth();
const myMessages = useQuery(api.messages.list, isSignedIn ? {...params} : "skip");
if "skip" is passed instead of arguments to useQuery the server won't be called
Elfinslayer
ElfinslayerOP14mo ago
oof, i had used that in another project and totally forgot about it. thanks!
Michal Srb
Michal Srb14mo ago
(if you follow Jamie's suggestion, use useConvexAuth or Authenticated from convex/react, as they wait not just for the auth provider but also for your Convex backend to receive the auth)

Did you find this page helpful?