How to integrate mongo with MoralisNextAuthProvider

Hi

I hope all is well.

I want to integrate mongo into my application. I am using MoralisNextAuthProvider with the following code found here:

import NextAuth from 'next-auth';
import { MoralisNextAuthProvider } from '@moralisweb3/next';

export default NextAuth({
    providers: [MoralisNextAuthProvider()],
    // adding user info to the user session object
    callbacks: {
        async jwt({ token, user }) {
            if (user) {
                token.user = user;
            }
            return token;
        },
        async session({ session, token }) {
            (session as { user: unknown }).user = token.user;
            return session;
        },
    },
});

I noticed on the Connect to a Database with Web3 Authentication tutorial, the code looks a bit different.

How can I achieve the above with MoralisNextAuthProvider? I tried a few ways but it didn’t work.

Thanks in advance.

you are referring to this code?

                    await connectDB();
                    const MongoUser = await Users.findOne({profileId: profileId})

Yes. How do I add that part.

I’m not sure, maybe you can integrate the code for MoralisNextAuthProvider and change it

You can get that data from the session once the user is authenticated

  const { data: session, status } = useSession();

  useEffect(() => {
    if (status === "authenticated") {
      console.log(session.user.profileId);
      //your database logic based on the profile id
    }
  }, [status]);

Thanks for reply. Tried something similar and your way, keep getting:

TypeError: Cannot destructure property 'auth' of 'urlObj' as it is null.

I managed to get the wallet address by using the user.address from the MoralisNextAuthProvider OperationResolver.

1 Like