Eyal Alfasi
Eyal Alfasi
CCConvex Community
Created by Eyal Alfasi on 10/22/2024 in #support-community
Authentication in Remix Loader with Convex Auth
I'm using Convex and Convex Auth in a Remix app, and I want to check if a user is authenticated in a Remix loader to redirect unauthenticated users to the login page. I'm trying this:
export const loader: LoaderFunction = () => {
const convex = new ConvexClient(CONVEX_URL);
const currentUser = convex.query(api.users.me, {});

if (currentUser === null) {
return redirect("/login");
}

return null;
};
export const loader: LoaderFunction = () => {
const convex = new ConvexClient(CONVEX_URL);
const currentUser = convex.query(api.users.me, {});

if (currentUser === null) {
return redirect("/login");
}

return null;
};
But currentUser always returns null. Using the useConvexAuth hook in a component does eventually return isAuthenticated as true so I know the login worked. Here’s my users.me query:
export const me = query({
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (userId === null) {
return null;
}
return await ctx.db.get(userId);
},
});
export const me = query({
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (userId === null) {
return null;
}
return await ctx.db.get(userId);
},
});
How can I correctly check user authentication in the loader? Or should I handle this redirect logic in remix + convex auth differently? Thanks in advance 🙂
20 replies