Error: Failed to construct 'URL': Invalid URL

When asking for help in this category, please make sure to provide the following details:

Also, kindly provide the Web3Auth initialization and login code snippet below. This will help us better understand your issue and provide you with the necessary assistance.

chainConfig.ts

const chainConfig = {
  chainId: "0xa455" || "0xaa36a7",
  rpcTarget: "http://5.78.118.91:8545/" || "null",
  chainNamespace: CHAIN_NAMESPACES.EIP155 as ChainNamespaceType,
  displayName: process.env.NEXT_PUBLIC_DISPLAY_NAME || "Ethereum Sepolia Testnet",
  blockExplorerUrl: process.env.NEXT_PUBLIC_BLOCK_EXPLORER_URL || "https://sepolia.etherscan.io",
  ticker: process.env.NEXT_PUBLIC_TICKER || "ETH",
  tickerName: process.env.NEXT_PUBLIC_TICKER_NAME || "Ethereum",
  logo: process.env.NEXT_PUBLIC_LOGO_URL || "https://cryptologos.cc/logos/ethereum-eth-logo.png",
};

const privateKeyProvider = new EthereumPrivateKeyProvider({
  config: { chainConfig },
});

const clientId = process.env.NEXT_PUBLIC_WEB3AUTH_CLIENTID2 || "null";

export const web3auth = new Web3Auth({
  clientId,
  web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
  privateKeyProvider,
});

useAuth.tsx

import type { IProvider } from "@web3auth/base";
import type { BigNumber } from "ethers";
import { ethers, providers } from "ethers";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { web3auth } from "../config/web3authConfig";

interface UserInfo {
  email: string;
  name: string;
}

export const useAuth = () => {
  const [provider, setProvider] = useState<providers.Web3Provider | null>(null);
  const [loggedIn, setLoggedIn] = useState(false);
  const [web3authInitialized, setWeb3authInitialized] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [account, setAccount] = useState<string | null>(null);
  const [balance, setBalance] = useState<string | null>(null);
  const router = useRouter();

  const formatBalance = (balance: BigNumber, decimals: number) => {
    const formatted = ethers.utils.formatUnits(balance, decimals);
    return parseFloat(formatted).toString();
  };

  useEffect(() => {
    const init = async () => {
      try {
        if (!web3authInitialized && !web3auth.connected) {
          console.log("Initializing Web3Auth...");
          await web3auth.initModal();
          setWeb3authInitialized(true);
          console.log("Initialized Web3Auth!!");
        }

        if (web3auth.connected && web3auth.provider) {
          console.log("Web3Auth connected and provider available");
          const ethersProvider = new providers.Web3Provider(web3auth.provider as providers.ExternalProvider);
          setProvider(ethersProvider);
          setLoggedIn(true);

          const user = await web3auth.getUserInfo();
          setUserInfo({
            email: user.email || "",
            name: user.name || "",
          });

          const signer = ethersProvider.getSigner();
          const address = await signer.getAddress();
          setAccount(address);

          const tokenAddress = process.env.NEXT_PUBLIC_ERC20_CONTRACT || "";
          const tokenABI = ["function balanceOf(address account) view returns (uint256)"];
          const tokenContract = new ethers.Contract(tokenAddress, tokenABI, ethersProvider);

          const balance: BigNumber = await tokenContract.balanceOf(address);
          setBalance(formatBalance(balance, 18));
        }
      } catch (error) {
        console.error("Initialization failed:", error);
      }
    };

    init();
  }, [web3authInitialized]);

  const login = async () => {
    try {
      console.log("로그인 체크 시작");
      const web3authProvider = await web3auth.connect();
      console.log("로그인 체크 끝");
      if (web3authProvider) {
        console.log("Web3Auth login successful");
        const ethersProvider = new providers.Web3Provider(web3authProvider as providers.ExternalProvider);
        setProvider(ethersProvider);
        setLoggedIn(true);

        const user = await web3auth.getUserInfo();
        setUserInfo({
          email: user.email || "",
          name: user.name || "",
        });

        const signer = ethersProvider.getSigner();
        const address = await signer.getAddress();
        setAccount(address);

        const tokenAddress = process.env.NEXT_PUBLIC_ERC20_CONTRACT || "";
        const tokenABI = ["function balanceOf(address account) view returns (uint256)"];
        const tokenContract = new ethers.Contract(tokenAddress, tokenABI, ethersProvider);

        const balance: BigNumber = await tokenContract.balanceOf(address);
        setBalance(formatBalance(balance, 18));
      }
    } catch (error) {
      console.error("Login failed:", error);
    }
  };

  const logout = async () => {
    try {
      await web3auth.logout();
      setProvider(null);
      setLoggedIn(false);
      setWeb3authInitialized(false);
      setUserInfo(null);
      setAccount(null);
      setBalance(null);
      console.log("Logged out");
      router.push("/");
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  const sendToken = () => {
    router.push("/payments");
  };

  const mintToken = () => {
    router.push("/minting");
  };

  return {
    provider,
    loggedIn,
    userInfo,
    account,
    balance,
    sendToken,
    mintToken,
    login,
    logout,
  };
};

When I click the Google login button, you encounter an error, and the execution stops at const web3authProvider = await web3auth.connect(); in login function. The Google login modal does not appear.

Everything works fine on localhost, but in the deployed environment(https://payments-monorepo.vercel.app/) , I encounter the above error. I have added the deployed URL to the whitelist, and changed the RPC URL from Sepolia testnet to L2 mainnet. I am using WEB3AUTH_NETWORK.SAPPHIRE_MAINNET.

hi @doniang1123

I hope you are doing great !

Here is a working example for the Modal SDK in Next.js: web3auth-pnp-examples/web-modal-sdk/quick-starts/nextjs-modal-quick-start at main · Web3Auth/web3auth-pnp-examples · GitHub

Could you attempt using this setup to determine if there are any issues with your current configuration?

Additionally, kindly review the useEffect showcased in the example, which executes on the initial render.

Please compare your implementation with the example and reach out if you encounter any challenges.

Thank you.

Hi @TomTom

Thanks for your help!!

I found out that I have the problem with this code.
const web3authProvider: IProvider | null = await web3auth.connect();

I set up the configuration file like this

const chainConfig = {
  chainId: process.env.NEXT_PUBLIC_CHAIN_ID || "0xa455",
  rpcTarget: process.env.NEXT_PUBLIC_RPC_URL || "null",
  chainNamespace: CHAIN_NAMESPACES.EIP155 as ChainNamespaceType,
  displayName: process.env.NEXT_PUBLIC_DISPLAY_NAME || "Ethereum Sepolia Testnet",
  blockExplorerUrl: process.env.NEXT_PUBLIC_BLOCK_EXPLORER_URL || "https://sepolia.etherscan.io",
  ticker: process.env.NEXT_PUBLIC_TICKER || "ETH",
  tickerName: process.env.NEXT_PUBLIC_TICKER_NAME || "Ethereum",
  logo: process.env.NEXT_PUBLIC_LOGO_URL || "https://cryptologos.cc/logos/ethereum-eth-logo.png",
};

const privateKeyProvider = new EthereumPrivateKeyProvider({
  config: { chainConfig },
});

const clientId = process.env.NEXT_PUBLIC_WEB3AUTH_CLIENTID || "null";

export const web3auth = new Web3Auth({
  clientId,
  web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
  privateKeyProvider,
});

NEXT_PUBLIC_RPC_URL is working well and I set up the client id at the image file I attached.


Currently, I am testing on localhost, but I plan to use it on a whitelisted URL later.

Here is error log

Thank you.

hi @doniang1123,
I hope you are ok ! Please clarify if the last issue is occurring on Localhost or online? If it is an online dapp, please whitelist it in the Dashboard.

Did you double-check the example I sent to you?

Seems like the rpcTarget you’re sending is invalid. Please check the url being sent

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