CORS Error with Moralis Web3 Authentication and Firebase Cloud Functions

Hello everyone,

I am currently developing a React application where I am using Moralis for Web3 authentication (via MetaMask, WalletConnect, and Phantom) and Firebase for authentication and cloud functions. I am encountering CORS issues that I can’t seem to figure out.

When I try to call the signInWithMoralisByEvm function from the @moralisweb3/client-firebase-evm-auth package, I get the following errors:

OPTIONS
https://us-central1-firebase-elgami.cloudfunctions.net/ext-moralis-auth-requestMessage
CORS Missing Allow Origin

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-firebase-elgami.cloudfunctions.net/ext-moralis-auth-requestMessage. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-firebase-elgami.cloudfunctions.net/ext-moralis-auth-requestMessage. (Reason: CORS request did not succeed). Status code: (null).

Here is the relevant part of my code:

import React, { useState, useEffect } from 'react';
import { signInWithMoralis as signInWithMoralisByEvm } from '@moralisweb3/client-firebase-evm-auth';
import { signInWithMoralis as signInWithMoralisBySolana } from '@moralisweb3/client-firebase-sol-auth';
import { httpsCallable } from 'firebase/functions';
import { User } from 'firebase/auth';
import { auth, functions, moralisAuth } from '../firebase';
import WalletConnectProvider from '@walletconnect/web3-provider';
import { Web3Provider } from '@ethersproject/providers';

function Login() {
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
  	console.log("Firebase User: ", auth.currentUser);
    setCurrentUser(auth.currentUser);
  }, []);

  async function signInWithMetamask() {
    try {
      const result = await signInWithMoralisByEvm(moralisAuth);
      console.log("Moralis User: ", result.credentials.user);
      setCurrentUser(result.credentials.user);
    } catch (error) {
      console.log('Error signing in with MetaMask:', error);
    }
  }

  async function signInWithWalletConnect() {
    localStorage.removeItem('walletconnect');

    const provider = new WalletConnectProvider({
      rpc: {
        1: 'https://mainnet.infura.io/v3/ef3da53f237c4a2e83f7905f6f159584',
      },
    });

    await provider.enable();

    const result = await signInWithMoralisByEvm(moralisAuth, {
      provider: new Web3Provider(provider),
    });

    setCurrentUser(result.credentials.user);
  }

  async function signInWithPhantom() {
    const result = await signInWithMoralisBySolana(moralisAuth);
    setCurrentUser(result.credentials.user);
  }

  async function signOut() {
    await auth.signOut();
    setCurrentUser(null);
  }

  async function getSecretData() {
    try {
      // Ensure there is a currently signed-in user
      if (!auth.currentUser) {
        throw new Error('No user currently signed in');
      }

      // Get the ID token of the currently signed-in user
      const idToken = await auth.currentUser.getIdToken();

      // Make an authenticated HTTP request to the getSecretData function
      const response = await fetch('https://us-central1-firebase-elgami.cloudfunctions.net/getSecretData', {
        headers: {
          'Authorization': `Bearer ${idToken}`
        }
      });

      if (!response.ok) {
        throw new Error('HTTP error ' + response.status);
      }

      const data = await response.json();
      alert(JSON.stringify(data));
    } catch (e) {
      console.log('Error getting secret data:', e);
      alert(e.message);
    }
  }

  return (
    <div className="App">
      <h1>🔒 Authenticate with Moralis Web3</h1>

      <p>
        Current user:&nbsp;
        <strong>
          {currentUser ? (
            <>
              address: {currentUser.displayName}, uid: {currentUser.uid}
            </>
          ) : (
            'unknown'
          )}
        </strong>
      </p>

      <h4>Authentication</h4><br /><br />

      <button onClick={signInWithMetamask}>Sign in with MetaMask</button><br /><br />

      <button onClick={signInWithWalletConnect}>Sign in with WalletConnect</button><br /><br />

      <button onClick={signInWithPhantom}>Sign in with Phantom</button><br /><br />

      <button onClick={signOut}>Sign out</button><br /><br />

      <button onClick={getSecretData}>Get secret data</button>
    </div>
  );
}

export default Login;

I’ve ensured that my Firebase cloud function does include the necessary CORS headers, but it seems like the error is coming from the signInWithMoralisByEvm function. I’m wondering if anyone else has encountered this issue and could provide some guidance.

Is the issue likely originating from the Moralis function or is it something to do with my setup? Any help would be greatly appreciated!

Thanks in advance.

Hi @MetalHorse233

Are you using the Firebase config of the same Firebase project where the fucntion is created? I think using the wrong Firebase config can also cause this error.

Could that be the case here?