[SOLVED] Trying to set up auth API for new self hosted server

Hi,
I am trying to migrate my website from moralis hosted to self hosted. I have my moralis parse server running locally and have changed all my .env setting to reflect it.

I wrote out all of the code from the react docs and replaced the old connect wallet button with the one from this new code for the api auth.

However, when I click on the button absolutely nothing happens. There is no api request logged in the network logs, no logs from the server showing a requestMessage function was called, and no message sign request on the front end.

my console logs get to the ā€œpassed the error checksā€ and thats itā€¦

I have been using an older version of the moralis sdk, but installed moralis-v1 for this purpose.

my code was originally an exact copy of the example, but I have altered it a bit trying to debug.

here is my code for the auth after some attempts at correcting the issue:

import { useMoralis } from "react-moralis";
import Moralis from "moralis-v1";
import { useState } from "react";
import { useChain } from "react-moralis";

export const Connect = () => {
  const { authenticate, enableWeb3, account } = useMoralis();
  const [authError, setAuthError] = useState(null);
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const { chainId } = useChain();
  async function handleAuth(provider) {
    try {
      setAuthError(null);
      setIsAuthenticating(true);
      console.log("starting auth");

      await enableWeb3({ throwOnError: true, provider });

      if (!account) {
        console.log("account error");
        throw new Error(
          "Connecting to chain failed, as no connected account was found",
        );
      }
      if (!chainId) {
        console.log("chain error");
        throw new Error("Connecting to chain failed, as no chain was found");
      }
      console.log("passed the error checks");
      const { message } = await Moralis.Cloud.run("requestMessage", {
        address: account,
        chain: parseInt(chainId, 16),
        network: "evm",
      });
      console.log("message set");
      await authenticate({
        signingMessage: message,
        throwOnError: true,
      });
      console.log("things ran correctly");
    } catch (error) {
      setAuthError(error);
    } finally {
      setIsAuthenticating(false);
    }
  }

  return (
    <div>
      <button onClick={() => handleAuth("metamask")}>
        Connect with Metamask
      </button>
    </div>
  );
};

EDIT:
I know that the front end is connected to the back end correctly because the getPluginSpecs function is being called

what do you get on console? no messages from that function ?

on client side console I get

starting auth
passed the error checks

nothing on server side

ok, so this is the line where it stops working

you can look in network tab to see what it tries to access when it executes that line

There is absolutely nothing triggered in the network tab when I run the function.

you have to click on the button after you open the network tab

Yes, after the page loads I go to the network tab and clear it to get rid of the unrelated stuff that happens on initial load.
Then I click the button, triggering the function
nothing happens.
That screenshot was taken after clicking the button.

also nothing in console log?
can you try with a simpler cloud function (like getServerTime)? and to call it directly with a postman? (you may have to use POST)

Iā€™m not very familiar with making api calls in react, so I may have done it wrong.

const result = await fetch(
        "http://localhost:1337/server/functions/getServerTime",
        { method: "POST" },
      );
      console.log(result);

results in a 403 error

Can you post your package.json?

console.log(ā€œmessage setā€);

You arenā€™t getting this logged? Can you log error from the try catch.

catch (error) {
  console.log("err", error);

package.json:

{
  "name": "gigautility",
  "version": "0.2.0",
  "dependencies": {
    "@ant-design/icons": "^4.7.0",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@walletconnect/web3-provider": "^1.6.6",
    "@web3auth/web3auth": "^2.1.3",
    "antd": "^4.16.13",
    "assert": "^2.0.0",
    "crypto-browserify": "^3.12.0",
    "https-browserify": "^1.0.0",
    "magic-sdk": "7.0.0",
    "moralis": "^1.2.3",
    "moralis-v1": "^1.11.0",
    "os-browserify": "^0.3.0",
    "react": "^17.0.2",
    "react-app-rewired": "^2.2.1",
    "react-blockies": "^1.4.1",
    "react-dom": "^17.0.2",
    "react-moralis": "^1.2.1",
    "react-query": "^3.39.1",
    "react-router": "^5.2.1",
    "react-router-dom": "^5.3.0",
    "react-scripts": "^5.0.0",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "url": "^0.11.0",
    "web-vitals": "^1.0.1",
    "yarn": "^1.22.17"
  },
  "scripts": {
    "start": "set \"GENERATE_SOURCEMAP=false\" && react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject",
    "devchain": "node Truffle/scripts/devChain.js",
    "connect": "moralis-admin-cli connect-local-devchain",
    "watch:events": "moralis-admin-cli add-contract",
    "deploy": "node Truffle/scripts/deployContract.js",
    "deploypage": "gh-pages -d build",
    "clean": "npx gh-pages-clean",
    "lint:check": "eslint .",
    "lint:fix": "eslint --fix",
    "prettier:check": "prettier --check .",
    "prettier:fix": "prettier --write \"**/*.{js,jsx,ts,tsx,css,md,json,html}\" .prettierrc --config ./.prettierrc",
    "format": "npm run lint:fix && npm run prettier:fix",
    "prepare": "husky install"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint": "^7.11.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.28.0",
    "eslint-plugin-react-hooks": "^4.3.0",
    "gh-pages": "^3.2.3",
    "husky": "^7.0.0",
    "lint": "^0.7.0",
    "prettier": "^2.5.1"
  }
}

error: err Error: You need to call Moralis.start with an applicationId before using Moralis.

Moralis is initialized in the app file, the connect button is in the header bar of the app file

or rather, Moralis is initiated in the index.js file, and isInitialized is checked in the app file

Can you try installing these versions (which are used in the migration client demo):

[email protected]
[email protected]

And remove [email protected].

That definitely did something. The request is going out now, and metamask is prompting for a message signing, but Iā€™m getting this new error

err Error: Moralis auth failed, invalid data
at handleError (RESTController.js:438:1)

Is your Parse server code the same as the demo or have you made any changes?

Can you also your Parse serverā€™s package.json.

server code should be the same, I dont recall making any changes

{
  "name": "demo-parse-server-migration",
  "version": "1.0.0",
  "main": "dist/index.js",
  "private": true,
  "dependencies": {
    "@codemirror/language": "^0.20.0",
    "@moralisweb3/core": "^2.2.0",
    "@types/node": "^18.7.15",
    "dotenv": "^16.0.1",
    "envalid": "7.3.1",
    "express": "^4.18.1",
    "express-rate-limit": "^6.5.1",
    "graphql": "^16.6.0",
    "graphql-ws": "^5.10.1",
    "moralis": "^2.2.0",
    "parse-server": "^5.2.5"
  },
  "devDependencies": {
    "@moralisweb3/eslint-config": "^1.0.0",
    "@typescript-eslint/eslint-plugin": "^5.12.0",
    "@typescript-eslint/parser": "^5.12.0",
    "axios": "^0.27.2",
    "eslint": "^8.9.0",
    "eslint-plugin-import": "^2.26.0",
    "mongodb-runner": "^4.9.0",
    "prettier": "^2.7.1",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4"
  },
  "scripts": {
    "dev": "ts-node src/index.ts",
    "start": "node build/index.js",
    "build": "tsc",
    "lint": "eslint --ext .js,.ts .",
    "format": "prettier --write 'src/**/*.{js,ts}'",
    "dev:db-start": "mongodb-runner start",
    "dev:db-stop": "mongodb-runner stop",
    "gen:cloud": "ts-node ./scripts/generateCloudCode.ts",
    "tsc": "tsc"
  }
}

Can you doublecheck both .env files for your Parse server and React app and that they more or less match (except for exact API key, Mongo/redis, etc.).

I dont recall making any changes

Can you post your Parse serverā€™s cloud/main.ts code. You arenā€™t getting any other errors in your browser console or both server terminals?

the server is getting the message request:
info: Ran cloud function requestMessage for user undefined with:
Input: {ā€œaddressā€:ā€œ0xb03139137d06db446faa490d8a6f07d411f849c0ā€,ā€œchainā€:1,ā€œnetworkā€:ā€œevmā€}

.env both look good

the only errors Iā€™m getting now is the invalid data one.

main.ts:

/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-var-requires */
declare const Parse: any;
import './generated/evmApi';
import './generated/solApi';
import { requestMessage } from '../auth/authService';

Parse.Cloud.define('requestMessage', async ({ params }: any) => {
  const { address, chain, network } = params;

  const message = await requestMessage({
    address,
    chain,
    network,
  });

  return { message };
});

Parse.Cloud.define('getPluginSpecs', () => {
  // Not implemented, only excists to remove client-side errors when using the moralis-v1 package
  return [];
});

Parse.Cloud.define('getServerTime', () => {
  // Not implemented, only excists to remove client-side errors when using the moralis-v1 package
  return null;
});

What happens if you run npm run build for the Parse server?

same results as if I use yarn build

It looks like the message request is returning 200, but the invalid data is coming from the auth call

the sign request only says ā€œMoralis Authenticationā€ and not the message written in auth/authservice.ts
I went in and changed the domain and uri in that file to localhost and rebuilt, but Iā€™m still getting the same error

Can you try authenticating with a clone of the migration client - you just need to copy over your .env file. Ideally you do the same with the parse server.

It would be easier to find out where the issue is starting from working baseline projects so we donā€™t have to make any assumptions about how youā€™ve set up your own server and React client.

For example, your current Parse server dependencies expects networkType, not network in requestMessage. On my end if I try using network, I get type errors when trying to build.