lucidL
Convex Community8mo ago
2 replies
lucid

convex auth - null user with fetchQuery on server

export const currentUser = query({
    args: {},
    handler: async (ctx) => {
        const userIdentity = await ctx.auth.getUserIdentity();
        console.log("server identity", await ctx.auth.getUserIdentity());
        console.log("server id", await getAuthUserId(ctx));
        const userId = await getAuthUserId(ctx);
        if (userId === null) {
            return null;
        }
        return await ctx.db.get(userId);
    },
});

const user = await fetchQuery(api.user.queries.currentUser);


In the convex logs Im seeing a successful log of the user Id. However when Im calling the fetchQuery in a layout file, the user is
null
. If i call this exact same query using useQuery in a client component, I see a user returned successfully

This is my middleware:
import {
    convexAuthNextjsMiddleware,
    createRouteMatcher,
    nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";

const isSignInPage = createRouteMatcher(["/login"]);
const isProtectedRoute = createRouteMatcher(["/(.*)"]);

export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
    if (isSignInPage(request) && (await convexAuth.isAuthenticated())) {
        return nextjsMiddlewareRedirect(request, "/");
    }
    if (
        isProtectedRoute(request) &&
        !(await convexAuth.isAuthenticated()) &&
        !isSignInPage(request)
    ) {
        return nextjsMiddlewareRedirect(request, "/login");
    }
});
export const config = {
    matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
Was this page helpful?