RayyR
Convex Community2y ago
18 replies
Rayy

Unable to authenticate Convex with next auth when provider is Credentials.

I have followed this post to setup the adapter https://stack.convex.dev/nextauth-adapter, and authenticate Convex with next auth, and it works with providers with github and google, but it does not with credentials.

I am able to authenticate in the client side still with credentials, but unable to authenticate the same with Convex. It is not returning any sessions with credentials provider.

Here is my auth.ts
export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  events: {
    async linkAccount({ user }) {
      await updateUserEmailVerification(user.id as Id<"users">);
    },
  },
  callbacks: {
    async signIn({ user, account }) {
      if (account?.provider !== "credentials") return true;

      if (!user.email) return false;

      const existingUser = await getUserByEmail(user.email);

      if (!existingUser?.emailVerified) return false;

      return true;
    },
    async session({ session }) {
      console.log(session);
      const privateKey = await importPKCS8(
        process.env.CONVEX_AUTH_PRIVATE_KEY!,
        "RS256"
      );
      const convexToken = await new SignJWT({
        sub: session.userId,
      })
        .setProtectedHeader({ alg: "RS256" })
        .setIssuedAt()
        .setIssuer(CONVEX_SITE_URL)
        .setAudience("convex")
        .setExpirationTime("1h")
        .sign(privateKey);
      return { ...session, convexToken };
    },
  },
  adapter: ConvexAdapter,
  ...authConfig,
});

declare module "next-auth" {
  interface Session {
    convexToken: string;
  }
}


I feel like I need to access the token callback to pass theJWT.
Have I missed something in the docs?
Was this page helpful?