#how do i get the userId when using convex and betterauth
4 messages · Page 1 of 1 (latest)
Hi @night shell. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To get the user ID when using Convex with Better Auth, you should use the Better Auth component client’s helper methods within your Convex backend functions.
The recommended approach is to use the auth component’s getAuthUser method, which returns the Better Auth user object for the currently authenticated user. From this object, you can access the user’s ID and other metadata.
Here’s an example:
import { query } from "./_generated/server";
import { authComponent } from "./auth";
export const getCurrentUser = query({
args: {},
handler: async (ctx) => {
// Returns the Better Auth user object for the current user
return await authComponent.getAuthUser(ctx);
},
});
If you specifically want the user’s ID, you can extract it from the returned object:
export const getCurrentUserId = query({
args: {},
handler: async (ctx) => {
const authUser = await authComponent.getAuthUser(ctx);
return authUser?._id ?? null; // This is the Better Auth user ID
},
});
If you need to look up your application’s user table (if you have a separate users table), you may need to query by an authId field that links your app user to the Better Auth user, as described in the migration guides. For example:
const authUser = await authComponent.getAuthUser(ctx);
const user = await ctx.db
.query("users")
.withIndex("authId", (q) => q.eq("authId", authUser._id))
.unique();
This will give you your app’s user document associated with the current Better Auth userBasic Usage: Authorization Migrate-userid: Update userId references.
Summary:
- Use
authComponent.getAuthUser(ctx)to get the Better Auth user object (including its ID). - If you have a separate app user table, link it via an
authIdfield and query by that.