How can I use Convex in the Next.js middleware?
I am trying to use Convex in my middleware like so, but
ctx.auth.getUserIdentity()
in my action keeps returning null
, I believe that this is due it running on the server so it is not wrapped with <ConvexProviderWithClerk />
:
4 Replies
You need to pass a valid token to fetchAction:
https://docs.convex.dev/client/react/nextjs/server-rendering#server-side-authentication
(it should say "preloadQuery, fetchQuery, fetchMutation and fetchAction")
Next.js Server Rendering | Convex Developer Hub
Next.js automatically renders both Client and Server Components on the server
Hmm, I think it might be possible to query the user from the db and pass in the
auth().userId
right?
Would this be more feasible option?You'll want to use a token to make sure the request is securely authenticated
fetchQuery(api.clerk.user.get, {}, {token: await auth().getToken({ template: "convex" }))})
Okay, thanks, will do that.