CodingWithJamal
CodingWithJamal15mo ago

React Server Components + Convex Auth State Support?

So im in my nextjs app the convex docs says to use the useConvexAuth hook.
const { isAuthenticated} = useConvexAuth();
const { isAuthenticated} = useConvexAuth();
hook makes sure that the browser has fetched the auth token needed to make authenticated requests to your Convex backend
However, 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
Aps
Aps15mo ago
From a convex function you can access the user identity as such:
import { mutation } from "./_generated/server";

export const myMutation = mutation({
args: {
// ...
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
const { tokenIdentifier, name, email } = identity!;
//...
},
});
import { mutation } from "./_generated/server";

export const myMutation = mutation({
args: {
// ...
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
const { tokenIdentifier, name, email } = identity!;
//...
},
});
Convex expects to find the jwt token in the Authorization header:
const jwtToken = "...";

fetch("https://<deployment name>.convex.site/myAction", {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
});
const jwtToken = "...";

fetch("https://<deployment name>.convex.site/myAction", {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
});
Since NextJS has its own backend, you would need to send this header manually and everything should work
CodingWithJamal
CodingWithJamalOP15mo ago
Okay thanks where can I find the jwt?
Michal Srb
Michal Srb15mo ago
@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.
CodingWithJamal
CodingWithJamalOP15mo ago
im using the clerk auth system
Michal Srb
Michal Srb15mo ago
In 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 server
Clerk
Next.js SSR authentication with Clerk
Next.js SSR authentication is easy with Clerk – just a few lines of code to get started.
CodingWithJamal
CodingWithJamalOP15mo ago
okay thanks

Did you find this page helpful?