#Get userId from auth token

3 messages · Page 1 of 1 (latest)

hidden harbor
#

I am in a nextjs middleware, can i access the user's id from the token without having to query my convex backend ?

prisma gullBOT
#

Hi @hidden harbor. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Short answer: Yes, if you’re using Convex Auth’s Next.js integration, you can read auth state (including whether a user is authenticated) directly in middleware, but you don’t get a raw userId string out of the box—you typically gate/redirect based on isAuthenticated there, and fetch the user (or userId) inside Convex functions.

  • In middleware, use convexAuthNextjsMiddleware and convexAuth.isAuthenticated() to protect routes and redirect without hitting Convex. [Authz Next.js]
  • If you need to preload data for server components, pass a token obtained via convexAuthNextjsToken() into preloadQuery/fetchQuery; your Convex query/mutation can then read the user via ctx.auth.getUserIdentity() or getAuthUserId(ctx). [Authz Next.js; Server-side auth; getAuthUserId]

If your goal is strictly “extract the Convex userId inside middleware without a Convex call,” the docs don’t provide a helper to decode the Convex JWT in middleware to a userId string. The recommended pattern is to use isAuthenticated in middleware, then resolve userId within Convex functions using getAuthUserId(ctx). [Authz Next.js; Use auth in backend functions]

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