Self Host Server Authentication in NextJs with next-auth

Hello.
I am trying to authenticate in a self host moralis server. As is specified on the docs, i am using moralis-v1.
With this code, i get some hydration errors from next when i use const { isConnected } = useAccount() from wagmi.
I also thing that with the docs code, there is not a available session as when i used next-auth some days ago.
I was writting something the following code to try to connect the wallet an store the session.

I changed the handleAuth function on index.js

async function handleAuth(provider) {
    try {
      setAuthError(null);
      setIsAuthenticating(true);

      await enableWeb3({ throwOnError: true, provider });
      const { account, chainId } = MoralisV1;

      const address = account;
      if (!address) {
        throw new Error(
          "Connecting to chain failed, as no connected address was found"
        );
      }
      if (!chainId) {
        throw new Error(
          "Connecting to chain failed, as no connected chain was found"
        );
      }

      const userData = { address, chain: chainId, network: "evm" };

      const { data } = await axios.post("/api/auth/request-message", userData, {
        headers: {
          "content-type": "application/json",
        },
      });

      let id, sessionToken;

      **await authenticate({**
**        signingMessage: data,**
**        throwOnError: true,**
**      })**.then(function (user) {
        id = user.id;
        sessionToken = user.getSessionToken();
      });

      const { url } = await signIn("credentials", {
        message: data,
        signature,
        redirect: false,
        callbackUrl: "/profile",
      });
      push(url);
    } catch (error) {
      setAuthError(error);
    } finally {
      setIsAuthenticating(false);
    }
  }

This is like an “hybrid” of the implementation of moralis v2 and moralis v1
I create /api/auth/request-message

import MoralisV1 from "moralis-v1/node";

const config = {
  domain: "auth.app",
  statement: "Please sign this message to confirm your identity.",
  uri: "http://localhost:3000",
  timeout: 60,
};

export default async function handler(req, res) {
  await MoralisV1.start({
    serverUrl: "${process.env.SERVER}",
    appId: "${process.env.APP}",
    apiKey: "${process.env.KEY}",
  });
  const { address, chain, network } = JSON.parse(req.body);

  try {
    const { message } = await MoralisV1.Cloud.run("requestMessage", {
      address: `${address}`,
      chain: parseInt(chain, 16),
      network: `${network}`,
      ...config,
    });

    res.status(200).json(message);
  } catch (error) {
    res.status(400).json({ error });
    console.error(error);
  }
}

api/auth/[…nextauth]

import CredentialsProvider from "next-auth/providers/credentials";
import NextAuth from "next-auth";
import MoralisV1 from "moralis-v1/node";

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "MoralisAuth",
      credentials: {
        message: {
          label: "Message",
          type: "text",
          placeholder: "0x0",
        },
        signature: {
          label: "Signature",
          type: "text",
          placeholder: "0x0",
        },
      },
      async authorize(credentials) {
        try {
          // "message" and "signature" are needed for authorization
          // we described them in "credentials" above
          const { message, signature } = credentials;

          await MoralisV1.start({
              serverUrl: "${process.env.SERVER}",
             appId: "${process.env.APP}",
             apiKey: "${process.env.KEY}",
          });
          const { address, profileId } = (
            **await MoralisV1.Auth.verify({ message, signature, network: "evm" })**
          ).raw;

          const user = { address, profileId, signature };
          // returning the user object and creating  a session
          return user;
        } catch (e) {
          console.error(e);
          return null;
        }
      },
    }),
  ],
  // adding user info to the user session object
  callbacks: {
    async jwt({ token, user }) {
      console.log("estoy en jwt");
      user && (token.user = user);
      return token;
    },
    async session({ session, token }) {
      session.user = token.user;
      return session;
    },
  },
});

So i was doing well until Moralis has to verify with the signature. When i sign, with the authenticate of moralis-v1 i can get some values like the id or the session but not the signature of the user.
Did you tried something like this?

Do you think that I changed many things that were not necessary or do you think that the way of authenticating without next-auth is insecure like me?

I can just go back to the docs and see how to render without errors again or search how to get the signature in moralis-v1.

Thanks for reading!

Any reason you’re trying to mix the two? It’s similar to using moralis-v1 / Moralis hosted servers where session data is stored in the client’s (app) local storage.

If you wanted to use JWT cookies from Next-Auth as the session, you would have to use different code instead of moralis-v1 to check against this session state for example - I’m not sure that would be worth the hassle.

Yes, the reason was to avoid the hydrate error. Now I think I should have solved it in another way.
I create some jwt user session cookies but without verifying the auth. Something like this:
/api/auth/[…nextauth]

import CredentialsProvider from "next-auth/providers/credentials";
import NextAuth from "next-auth";

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "MoralisAuth",
      credentials: {
        message: {
          label: "Message",
          type: "text",
          placeholder: "0x0",
        },
        signature: {
          label: "Signature",
          type: "text",
          placeholder: "0x0",
        },
      },
      async authorize(credentials) {
        try {
          const { message, signature, address } = credentials;

          const user = { message, signature, address };

          return user;
        } catch (e) {
          console.error(e);
          return null;
        }
      },
    }),
  ],
  // adding user info to the user session object
  callbacks: {
    async jwt({ token, user }) {
      user && (token.user = user);
      return token;
    },
    async session({ session, token }) {
      session.user = token.user;
      return session;
    },
  },
});

I dont thing is secure at all. I will change it as soon as possible.
Thanks for replying.