To send the anonymous user ID to the backend and access it during the account upgrade (e.g., when signing in with Google), you need to implement a mechanism to persist and retrieve this ID. The recommended approach, as discussed in the Convex community, is to use a pivot table or similar server-side storage to temporarily associate the anonymous user ID with the intended email or session.
How to Send and Access the Anonymous User ID
1. Store the Anonymous User ID Before Google Sign-In
When the user is still anonymous, get their user ID on the client (e.g., via a query to your backend using getAuthUserId). Before starting the Google sign-in, call a Convex mutation to store a mapping of the anonymous user ID and the email they intend to use for Google sign-in.
export const storeAnonMapping = mutation({
args: { anonUserId: v.id("users"), email: v.string() },
handler: async (ctx, args) => {
await ctx.db.insert("anonToEmail", {
anonUserId: args.anonUserId,
email: args.email,
});
},
});
2. Retrieve the Anonymous User ID in the Callback
After the user completes Google sign-in, in your custom createOrUpdateUser callback, look up the mapping in your anonToEmail table using the email from the Google profile. If a mapping exists, you have the anonymous user ID and can transfer the data.
const mapping = await ctx.db
.query("anonToEmail")
.withIndex("by_email", (q) => q.eq("email", args.profile.email))
.unique();
if (mapping) {
const anonUserId = mapping.anonUserId;
await ctx.db.delete(mapping._id);
}