#Get userId from auth token
3 messages · Page 1 of 1 (latest)
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]