React Server Components + Convex Auth State Support?
So im in my nextjs app the convex docs says to use the
useConvexAuth
hook.
hook makes sure that the browser has fetched the auth token needed to make authenticated requests to your Convex backendHowever, you cant use Hooks in RSC, so is it not possible for convex to know the auth state on the server side? Im asking because i want to fetch data on the server side and pass it to my client components as props. Avoiding having to do a lot of api calls from the client side. I know I can use the Js http client but im not sure how to handle auth session from there. And I want most of my business logic to stay on the server.
6 Replies
From a convex function you can access the user identity as such:
Convex expects to find the jwt token in the
Authorization
header:
Since NextJS has its own backend, you would need to send this header manually and everything should workOkay thanks
where can I find the jwt?
@CodingWithJamal how to get the token depends on your auth solution (say Clerk or Auth0 will have some getAccessToken method that can be called server side).
With ConvexHTTPClient you just call
client.setAuth(token)
, and from then on your queries/mutations etc will be authed and the server side code above should work.
If you need help getting the token let us know which Auth solution you’re using.im using the
clerk
auth systemIn that case this article should be relevant:
https://clerk.com/blog/next-js-ssr-authentication-with-clerk?utm_source=www.google.com&utm_medium=referral&utm_campaign=none#retrieving-user-id-or-jwt-templates
const token = await getToken({ template: 'convex' });
should get you the token on the serverClerk
Next.js SSR authentication with Clerk
Next.js SSR authentication is easy with Clerk – just a few lines of code to get started.
okay thanks