Client Connection

Overview

This guide will teach you how to connect to your self-hosted Moralis Server from different client environments. We will help you set up those.

Important

The completion of the Local Environment Setup is required to continue. The completion of the Production Environment Setup is NOT required but it is strongly recommended.

React App

Get the sample project

To speed up the connection process, we have the parse-server-migration-react-client project ready for you.

This project uses react-moralis, which is a thin wrapper on Moralis-JS-SDK-v1.

Download it and open it with your code editor:

Installation

Open the terminal and install dependencies by running:

yarn install

Configuration

Run the following command to get the .env file:

cp .env.example .env

Set the REACT_APP_SERVER_URL to your SERVER_URL:

REACT_APP_SERVER_URL = 'http://localhost:1337/server'

Your SERVER_URL will be different if you're already running your Moralis Server in a hosting service.

Set the REACT_APP_APPLICATION_ID to your APPLICATION_ID:

REACT_APP_APPLICATION_ID = 001

Testing

Make sure your self-hosted Moralis Server is running, locally or in a hosting service.

Run the client locally:

yarn start

Now you can try to Authenticate and for example getBlock data:

You have connected your self-hosted Moralis Server with a React App.

Note about Authentication

The following information serves as a good-to-know. The parse-server-migration-react-client project already implements it.

The authentication flow differs slightly between the self-hosted Moralis Server and the Moralis-hosted Server. This is because the first is using the Auth Api.

The following code snippets show how to handle it on a react-moralis app and how you would do it with Moralis-JS-SDK-v1 alone.

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

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

export const Example = () => {
  const { authenticate, enableWeb3 } = useMoralis();
  const [authError, setAuthError] = useState(null);
  const [isAuthenticating, setIsAuthenticating] = useState(false);

  const handleAuth = async (provider) => {
    try {
      setAuthError(null);
      setIsAuthenticating(true);

      // Enable web3 to get user address and chain
      await enableWeb3({ throwOnError: true, provider });
      const { account, chainId } = Moralis;

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

      // Get message to sign from the auth api
      const { message } = await Moralis.Cloud.run("requestMessage", {
        address: account,
        chain: parseInt(chainId, 16),
        network: "evm",
      });

      // Authenticate and login via parse
      await authenticate({
        signingMessage: message,
        throwOnError: true,
      });
    } catch (error) {
      setAuthError(error);
    } finally {
      setIsAuthenticating(false);
    }
  };

  return (
    <div>
      <button onClick={() => handleAuth("metamask")}>
        Authenticate via metamask
      </button>
    </div>
  );
};
async function handleAuth(provider) {
  await Moralis.enableWeb3({
    throwOnError: true,
    provider,
  });

  const { account, chainId } = Moralis;

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

  const { message } = await Moralis.Cloud.run("requestMessage", {
    address: account,
    chain: parseInt(chainId, 16),
    network: "evm",
  });

  await Moralis.authenticate({
    signingMessage: message,
    throwOnError: true,
  }).then((user) => {
    console.log(user);
  });
}

// Example
handleAuth("metamask");

Unity client

Overview

We will use the last release of the unity-web3-game-kit which is a wrapper around web3-unity-sdk.

Installation

Download the .unitypackage and drag it into your Unity project:

Import all the files:

The Moralis Web3 Setup panel will appear. Enter your SERVER_URL and your APPLICATION_ID and choose Done:

Your SERVER_URL will be different if you're already running your Moralis Server in a hosting service.

Configuration

Overview

To use the unity-web3-game-kit with your self-hosted Moralis Server you need to apply some modifications to the package.

This section goes through all the steps but if you need help you can head over to the related forum thread.

Open Packages > Moralis Web3 Unity SDK > Runtime > Kits > AuthenticationKit > Scripts > AuthenticationKit.cs:

Replace the code block from lines 257 to 263 (both included) for the following:

if (serverTimeResponse != null)
{
    Debug.LogError("Failed to retrieve server time from Moralis Server!");
}

IDictionary<string, object> requestMessageParams = new Dictionary<string, object>();

requestMessageParams.Add("address", address);
requestMessageParams.Add("chain", Web3GL.ChainId());

Dictionary<string, object> authMessage = await Moralis.Cloud.RunAsync<Dictionary<string, object>>("requestMessage", requestMessageParams);

string signMessage = authMessage["message"].ToString();

Replace the code block from lines 361 to 367 (both included) for the following:

if (serverTimeResponse != null)
{
    Debug.LogError("Failed to retrieve server time from Moralis Server!");
}

IDictionary<string, object> requestMessageParams = new Dictionary<string, object>();

requestMessageParams.Add("address", address);
requestMessageParams.Add("chain", session.ChainId);

Dictionary<string, object> authMessage = await Moralis.Cloud.RunAsync<Dictionary<string, object>>("requestMessage", requestMessageParams);

string signMessage = authMessage["message"].ToString();

Open Packages > Moralis Web3 Unity SDK > Runtime > Core > Platform > Services > ClientServices > MoralisUserService.cs and at line 101 add:

user.authData.Clear();

Open Moralis Web3 Unity SDK > Runtime > Web3Api > Client > ApiClient.cs and under existing default headers (line 40) add:

_defaultHeaderMap.Add("x-parse-application-id", Moralis.DappId);

Instead of this last modification, you could add the following to your server's src/index.ts:

app.use("/server/functions/:functionName", (req, res, next) => {
  req.headers["x-parse-application-id"] = "[YOUR_APPLICATION_ID]";
  next();
});

app.use(`/server`, parseServer);

Testing

Open Assets > Moralis Web3 Unity SDK > Demos > Introduction > Introduction.unity scene and run it. Now choose Connect:

After signing the authentication message you should see the following screen:

This setup is also tested and working on WebGL.

You have connected your self-hosted Moralis Server with a Unity project.

Last updated