ERROR Moralis[nextjs]: Unknown error in MoralisNextApi: Operation requestChallengeEvm has no group name in auth {

I am trying to authenticate via metamask, I followed this guide https://docs.moralis.io/web3-data-api/quickstart-nextjs but I am constantly getting the above error.
I am new to moralis

2 Likes

what line gives that error or where from it is?

Hi ! I am stuck too with the same error message (Error: Operation requestChallengeEvm has no group name in auth) That is really annoying cause I have tried for hours since yesterday to past that error but apparently I failed. Please help !

[…nextauth].ts

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;
    },
  },
});

[…moralis].ts

import { MoralisNextApi } from '@moralisweb3/next';

export default MoralisNextApi({
  apiKey: process.env.MORALIS_API_KEY,
  authentication: {
    domain: 'amazing.dapp',
    uri: process.env.NEXTAUTH_URL,
    timeout: 120,
  },
});

signin.jsx

import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { signIn } from "next-auth/react";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useRouter } from "next/router";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";

function SignIn() {
  const { connectAsync } = useConnect();
  const { disconnectAsync } = useDisconnect();
  const { isConnected } = useAccount();
  const { signMessageAsync } = useSignMessage();
  const { requestChallengeAsync } = useAuthRequestChallengeEvm();
  const { push } = useRouter();

  const handleAuth = async () => {
    if (isConnected) {
      await disconnectAsync();
    }

    const { account, chain } = await connectAsync({
      connector: new MetaMaskConnector(),
    });

    const { message } = await requestChallengeAsync({
      address: account,
      chainId: chain.id,
    });

    const signature = await signMessageAsync({ message });

    // redirect user after success authentication to '/user' page
    const { url } = await signIn("moralis-auth", {
      message,
      signature,
      redirect: false,
      callbackUrl: "/user",
    });
    /**
     * instead of using signIn(..., redirect: "/user")
     * we get the url from callback and push it to the router to avoid page refreshing
     */
    push(url);
  };

  return (
    <div>
      <h3>Web3 Authentication</h3>
      <button onClick={handleAuth}>Authenticate via Metamask</button>
    </div>
  );
}

export default SignIn;

what version of moralis sdk you are using? can you try with different versions of the SDK?

can you add some logging server side to find out from what line you get that error?

Here are the settings with moralis sdk version used:

{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "author": "Kroustof",
  "license": "ISC",
  "dependencies": {
    "@moralisweb3/next": "^2.11.1",
    "axios": "^0.27.2",
    "ethers": "^5.7.2",
    "moralis": "2.9.0",
    "next": "^13.1.2",
    "next-auth": "^4.18.8",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "wagmi": "^0.10.10"
  },
  "devDependencies": {
    "@types/react": "18.0.26",
    "typescript": "4.9.4"
  }
}


Could you share with us the package.json you use that actually works please ?

I also tried moralis version 2.9.0 and 2.8.0, but I have the same result…

Can you tell me what server side logging do you need ? Thanks

It looks like it works with version 2.11.0

We’ll have to check latest version

3 Likes

It works with that version. BIG THANKS TO YOU !

3 Likes
Unhandled Runtime Error
AxiosError: Internal Server Error

Call Stack
settle
node_modules/@moralisweb3/next/node_modules/axios/dist/browser/axios.cjs (1899:0)
XMLHttpRequest.onloadend
node_modules/@moralisweb3/next/node_modules/axios/dist/browser/axios.cjs (2208:0)

from yesterday nextjs app went crazy :frowning:

This error is from nextjs backend?

How did you get this error? What are you trying to do?

  const handleAuth = async (val) => {
    if (isConnected) {
      await disconnectAsync();
    }
    const userData = { network: "evm" };

    if (val === "meta") {
      const { account, chain } = await connectAsync({
        connector: new MetaMaskConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }
    if (val === "coin") {
      const { account, chain } = await connectAsync({
        connector: new CoinbaseWalletConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }

    if (val === "wallet") {
      const { account, chain } = await connectAsync({
        connector: new WalletConnectConnector({ options: { qrcode: true } }),
      });
      userData.address = account;
      userData.chain = chain.id;
    }

    if (val === "trust") {
      const { account, chain } = await connectAsync({
        connector: new InjectedConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }
    if (val === "ledger") {
      const { account, chain } = await connectAsync({
        connector: new LedgerConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }

    const { message } = await requestChallengeAsync({
      address: userData.address,
      chainId: userData.chain,
    });

    const signature = await signMessageAsync({ message });

    // redirect user after success authentication to '/user' page
    const { url } = await signIn("moralis-auth", {
      message,
      signature,
      redirect: false,
      callbackUrl: "/connect",
    });
    /**
     * instead of using signIn(..., redirect: "/user")
     * we get the url from callback and push it to the router to avoid page refreshing
     */

    push(url);
  };
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.user = token.user;
      return session;
    },
  },
});
import { MoralisNextApi } from "@moralisweb3/next";

export default MoralisNextApi({
  apiKey: process.env.MORALIS_API_KEY,
  authentication: {
    domain: "amazing.dapp",
    uri: process.env.NEXTAUTH_URL,
    timeout: 120,
  },
});

got it to work made some changes to the […moralis].js file and added a request-message.js to the api route using jays tutorial .

import { MoralisNextApi } from "@moralisweb3/next";

export default MoralisNextApi({ apiKey: process.env.MORALIS_API_KEY });

import CredentialsProvider from "next-auth/providers/credentials";
import NextAuth from "next-auth";
import Moralis from "moralis";
import connectDB from "../../../lib/connectDB";
import Users from "../../../lib/userSchema";
import * as fs from "fs";

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "MoralisAuth",

      async authorize(credentials) {
        try {
          const { message, signature } = credentials;

          const { address, profileId, expirationTime } = (
            await Moralis.Auth.verify({ message, signature, network: "evm" })
          ).raw;

          const user = { address, profileId, expirationTime, signature };

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

          const data = await fs.readFileSync("pages/api/auth/dp.jpg");
          let base64 = data.toString("base64");

          const img = new Buffer.from(base64, "base64");

          if (!MongoUser) {
            const newUser = new Users({
              profileId: profileId,
              account: address,
              signature: signature,
              displayPic: {
                data: img,
                contentType: "image/jpg",
              },
            });
            await newUser.save();
          }

          return user;
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error(e);
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      user && (token.user = user);
      return token;
    },
    async session({ session, token }) {
      session.expires = token.user.expirationTime;
      session.user = token.user;
      return session;
    },
  },
  session: {
    strategy: "jwt",
  },
});

import Moralis from "moralis";

const config = {
  domain: process.env.APP_DOMAIN,
  statement: "Please sign this message to confirm your identity.",
  uri: process.env.NEXTAUTH_URL,
  timeout: 60,
};

export default async function handler(req, res) {
  const { address, chain, network } = req.body;

  console.log(Moralis);
  try {
    const message = await Moralis.Auth.requestMessage({
      address,
      chain,
      network,
      ...config,
    });

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

import { Modal } from "antd";
import { useState } from "react";
import Image from "next/image";
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { InjectedConnector } from "wagmi/connectors/injected";
import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet";
import { WalletConnectConnector } from "wagmi/connectors/walletConnect";
import { signIn, getSession } from "next-auth/react";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";
import { useConnect, useSignMessage, useDisconnect, useAccount } from "wagmi";
import { useRouter } from "next/router";
import meta from "../public/assets/metamask.png";
import walletConnect from "../public/assets/WalletConnect.png";
import coin from "../public/assets/coinbase.webp";
import trust from "../public/assets/trust.jpg";
import ledger from "../public/assets/ledger.png";
import { LedgerConnector } from "wagmi/connectors/ledger";
import axios from "axios";
function Account({ user }) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { isConnected } = useAccount();
  const { connectAsync, connectors } = useConnect();
  const { disconnectAsync } = useDisconnect();
  const { push } = useRouter();
  const { signMessageAsync } = useSignMessage();
  const { requestChallengeAsync } = useAuthRequestChallengeEvm();
  // Handles Auth SignIn Function

  const handleAuth = async (val) => {
    if (isConnected) {
      await disconnectAsync();
    }
    const userData = { network: "evm" };

    if (val === "meta") {
      const { account, chain } = await connectAsync({
        connector: new MetaMaskConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }
    if (val === "coin") {
      const { account, chain } = await connectAsync({
        connector: new CoinbaseWalletConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }

    if (val === "wallet") {
      const { account, chain } = await connectAsync({
        connector: new WalletConnectConnector({ options: { qrcode: true } }),
      });
      userData.address = account;
      userData.chain = chain.id;
    }

    if (val === "trust") {
      const { account, chain } = await connectAsync({
        connector: new InjectedConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }
    if (val === "ledger") {
      const { account, chain } = await connectAsync({
        connector: new LedgerConnector({}),
      });
      userData.address = account;
      userData.chain = chain.id;
    }

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

    const message = data.message;

    const signature = await signMessageAsync({ message });

    // redirect user after success authentication to '/user' page
    const { url } = await signIn("credentials", {
      message,
      signature,
      redirect: false,
      callbackUrl: "/connect",
    });
    /**
     * instead of using signIn(..., redirect: "/user")
     * we get the url from callback and push it to the router to avoid page refreshing
     */

    push(url);
  };


This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.