Quick Start

Get Your First dApp Up and Running with Moralis.

Create a Moralis Server Instance

To get started, sign up for a free account at moralis.io. Once you've logged in, click on "Create a new App."

Mainnet vs Testnet vs Local

There are three environment choices when a new instance is created. Moralis can sync transactions from multiple blockchains simultaneously however, only one of each blockchain within the same group from either the mainnet or testnet can be synced at the same time.

  • YES ✅: Polygon Mainnet + Binance Smart Chain Mainnet

  • YES ✅: Polygon Testnet (Mumbai) + Binance SmartChain Testnet

  • NO❌: Etherem Mainnet + Polygon Testnet (Mumbai)

  • NO❌: Ganache (Local) + Ethereum Testnet (Ropsten)

To use both mainnet AND testnet requires creating 2 separate server instances.

Mainnet Server

Choosing mainnet will connect your Moralis Server to the production "for keeps" blockchain. Transactions on mainnet have real financial consequences.

For dApps that only read from the blockchain- like a portfolio app- it's perfectly safe to create a server directly on mainnet.

Testnet Server

Exactly like mainnet, but for testing. All tokens on testnets are worthless. In fact, there are faucets where developers can get tokens to test with for free. Testnet is a great "staging" environment for final testing before deploying to mainnet.

Local Devchain Server

This is a blockchain that runs locally on your computer. When building your smart contracts, you'll probably want to start with a local devchain such as Ganache or Hardhat, as these are really fast. You have full control over a local chain, which comes in handy for creating unit tests.

Choose Chains

Choose a name, select your desired location, and choose which networks (blockchains) your app needs to connect to (or all of them!).

You can choose multiple or all blockchains!

It will take a few minutes for the server to spin up. Once it's finished it will look something like this:

Moralis Server instance.

Expand the server instance to view more details by pressing the "..." button.

Expanded server view.
  • The "Dashboard" is the "nuts and bolts" view where you can see all the database tables and logs.

  • Install plugins to extend the functionality of your Moralis Server.

  • ​Cloud functions are custom functions that run on the server instead of the client.

  • The "Update/Restart" button updates the server to the latest version or, it pretty much means to "turn it off and on again!"

Setting Up Local Devchain (optional)

When building new smart contracts you need a fast and controlled testing environment. This is where hosting your own local blockchain is extremely useful. If you're new to Web3 development, this part can be skipped, use mainnet or testnet instead since there's plenty you can do with Moralis by using existing smart contracts, transactions, and authentication.

To connect Moralis to Ganache or Hardhat, check out the video tutorials in the "Ganache & Hardhat Setup" section linked below.

Email Configuration (optional)

Moralis supports sending emails to users. Click the "View Details" button on your server instance then the "Email Configuration" tab. You will need to sign up for a SendGrid account and provide the following:

  • API key.

  • From Email: This will appear as the "from" address on emails received by users (must be authorized by Sendgrid as a single sender or domain).

  • Sendgrid Verification Email Template ID: The template to use for the verification email.

  • Sendgrid Password Reset Template ID: The template to use for the password reset email.

See the "Sending Emails" page for more details.

Install the SDK

Via CDN

The fastest way to get the Moralis SDK into your JavaScript project is through npmcdn available at https://unpkg.com/moralis/dist/moralis.js.

<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
</head>

DON'T USE "LATEST" IN PRODUCTION, ALWAYS SPECIFY THE VERSION

In production, make sure to specify the specific version to guard against malicious package updates.

You can use npm info moralis versions to obtain a list of the available versions and replace <VERSION> below with the latest value.

<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]<VERSION>/dist/web3.min.js"></script>
<script src="https://unpkg.com/[email protected]<VERSION>/dist/moralis.js"></script>
</head>

Via NPM

For larger projects use the npm module.

npm install moralis

Browser

Then include it as usual.

const Moralis = require('moralis');

NodeJs

For server-side applications or NodeJs command-line tools, include:

// In a node environment
const Moralis = require('moralis/node');

Moralis Snippets

To help you code fast you can make use of Moralis Snippets available as an extension to Visual Studio Code.

With the extension installed, begin by typing: "moralis" anywhere inside a JavaScript file.

You will get IntelliSense for the available snippets.

Initialize Moralis

In order to use Moralis in your code, it needs to be initialized. You'll need the Server URL and APP ID. These can be found by pressing the "View Details" button on the server instance created above.

Moralis.initialize("YOUR_APP_ID");
​
Moralis.serverURL = 'https://YOUR_MORALIS_SERVER:1337/server'

⚠️ Please note: The master key should only be used in safe environments and never on the client-side! If the master key needs to be provided, use the following:

Moralis.initialize("YOUR_APP_ID", "", "YOUR_MASTERKEY");
​
Moralis.serverURL = 'https://YOUR_MORALIS_SERVER:1337/server'

The JavaScript SDK is originally based on the popular Backbone.js framework, but it provides flexible APIs that'll allow it to be paired with your favorite JS libraries. Our goal is to minimize configuration and let you quickly start building your JavaScript and HTML5 app on Moralis.

The SDK supports Firefox 23+, Chrome 17+, Safari 5+, and IE 10. IE 9 is supported only for apps that are hosted with HTTPS.

Authentication

Authenticating new users with Web3 is as simple as:

Moralis.authenticate().then(function (user) {
console.log(user.get('ethAddress'))
})

This will prompt the user to connect a Web3 wallet such as MetaMask and request a signature. Once the signature is verified, the promise will resolve with a User object.

Logout

await Moralis.User.logOut();

How to Authenticate With MetaMask, Web3 Development - Ivan on Tech

How to Merge MetaMask Addresses? Web3 Programming Tutorial - Ivan on Tech

User

Current

Once the user has been authenticated, the User object can be retrieved from anywhere with:

const user = Moralis.User.current();

The current user will always be authenticated. If there is no logged-in user Moralis.User.current() will return null.

Getting Attributes

The User object itself looks like the following:

{
className: "_User",
id: "EFurGjRPhl",
_objCount: 0,
attributes: {
ACL: ParseACL {permissionsById: {…}},
accounts: ["0xda...cb83"],
authData: {moralisEth: {…}},
createdAt: Date,
ethAddress: "0xda...cb83",
sessionToken: "r:3be8c91cb4db8fe2f154021f96496f49",
updatedAt: Date,
username: "Y9jPGr0H1TcMFHUpYZPjj9xhE",
}
}

There are two methods for getting user attributes:

const user = Moralis.User.current();
​
const userAddress = user.get("ethAddress");
const username = user.attributes.username;

Setting Attributes

Always use the set() method to change user attributes. Then call save(). Any new attributes will be created automatically.

user.set("phone", "555-555-1234");
user.set("birthDate", "2000-01-01");
await user.save();

For more details see the "Users" section.

Queries

Creating

Once you have data stored in Moralis, you'll probably want to use it! The foundation of retrieving data is by using the Query function. A query describes what data to retrieve and from where.

// set the collection to query
const collectionName = "EthTokenBalance";
const query = new Moralis.Query(collectionName);

Constraints

To filter the data returned by a query, all the usual constraints like equalTo, notEqualTo, greaterThan, lessThanOrEqualTo, containedIn, and limit are available. The query object uses similar syntax as MongoDB queries.

// users with DOGE tokens
query.equalTo("symbol", "DOGE");
​
// where the balance > 0
query.greaterThan("balance", 0);
​
// at most 10 results
query.limit(10);
​
const results = await query.find();

Sorting

The data can also be sorted according to specific attributes using the ascending and descending functions.

// highest to lowest balance
query.descending("balance");

Results

Once the query is constructed the results can be obtained by using find.

const results = await query.find();
// [EthTokenBalance, EthTokenBalance, ...]

Or only the first.

// get a specific user by email
const query = new Moralis.Query(Moralis.User);
query.equalTo("email", "[email protected]");
​
const user = await query.first();
// {id: "23r2r2qawsdf", attributes: {...} }

For more details see the "Queries" page.

Historical Transaction Data

Whenever a new user is authenticated via Web3, all of their transactions are synced by Moralis into the EthTransactions collection. This data can then be queried.

// get all ETH transactions made by the user
const user = Moralis.User.current();
const transQuery = new Moralis.Query("EthTransactions");
transQuery.equalTo("from_address", user.get("ethAddress"));
​
const results = await transQuery.find();
console.log(results);
// [EthTransaction, EthTransaction, ...]

Note that querying user-related data such as transactions requires permissions governed by the Access Control List (ACL). This means any data private to a specific user, such as transactions, can only be queried by that user. Querying data from other users (like finding someone's profile) requires using the MasterKey. For security reasons, the master key should only be used on the server inside cloud functions.

Real-Time Data

Historical data is great, but what if you're building a blog site and want to display a special message whenever a new user buys your BLOG token? This is where live queries come in. In addition to grabbing the historical results with find(), a query can be subscribed to!

// BLOG token holders
const query = new Moralis.Query("EthTokenBalance");
query.equalTo("symbol", "BLOG");
query.greaterThan("balance", 0);
​
// subscribe for real-time updates
const subscription = await query.subscribe();
​
// handle events
subscription.on("create", function(data) {
console.log(data.attributes.address, " has joined the BLOG army!");
});

This will cause an event to be fired whenever the dataset defined by the query changes.

  • create: When a new object is created and fulfills the query.

  • update: When an existing object in the query is updated and both the old and new values satisfy the query.

  • enter: When an existing object's old values did not satisfy the query but the new values do.

  • leave: When an existing object's old values satisfied the query but new values do not.

  • delete: When an existing object is deleted.

Live queries can be created for any other collection as well. See the "Live Query" page for more details. You can get more information on how to receive real-time updates on smart contract events on the "Real-Time Transactions" page under the "Transactions and Balances" section.

Ethereum Real-Time and Historical Transactions - Web3 Programming