#Convex auth get userId on server

3 messages · Page 1 of 1 (latest)

eternal palm
#

next.js get userId on server

brisk gateBOT
#

Hi @eternal palm. 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 current user's ID on the server when using Convex Auth in a Next.js app, you should use the helper function getAuthUserId from @convex-dev/auth/server. This function works inside Convex query, mutation, or action functions and returns the authenticated user's ID, or null if the client isn't authenticated.

Here’s a typical usage example:

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; // or throw an error if authentication is required
    }
    return await ctx.db.get(userId);
  },
});
  • Use this pattern in your Convex backend functions to securely access the user ID.
  • This approach is recommended for Convex Auth and is not applicable to Clerk, Auth0, or other providers, which have their own methods for accessing user identity.

For more details, see the official documentation: Use authentication state in backend functions, getAuthUserId API reference.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: