much 2 yearnM
Convex Community2y ago
5 replies
much 2 yearn

Best practice to get userId from from user user in function

in the next/expo monorepo they use getting the userId from the userIdentity, but unsure if this is best practice in case this value will change among auth providers and also because it default to type string and not
Id<"users">
. Is there a way to get userId from the auth flow for your functions or is the best way to pass the userId as an argument from the frontend?

export const getUserId = async (ctx: { auth: Auth }) => {
  return (await ctx.auth.getUserIdentity())?.subject;
};

// Get all notes for a specific user
  export const getNotes = query({
    args: {},
    handler: async (ctx) => {
    const userId = await getUserId(ctx);
    if (!userId) return null;

    const notes = await ctx.db
      .query('notes')
      .filter((q) => q.eq(q.field('userId'), userId))
      .collect();

    return notes;
  },
});


vs

 export const getNotes = query({
    args: {
      userId: Id<"users">
    },
    handler: async (ctx, args) => {
       const identity = await ctx.auth.getUserIdentity();
        if (identity === null) {
          throw new Error("Unauthenticated call to mutation");
        }

    const notes = await ctx.db
      .query('notes')
      .filter((q) => q.eq(q.field('userId'), args.userId))
      .collect();

    return notes;
  },
});
Was this page helpful?