Using NextJS

This tutorial will teach you how to set up a NextJS dapp that can query blockchain data such as NFTs, tokens, balances, transfers, transactions, and more from any NextJS application. Also, this tutorial works on almost any blockchain, including Ethereum, Polygon, BNB Chain, Avalanche, Cronos, and many more!

Introduction

This tutorial illustrates how you can create a basic NextJS dapp that uses the Moralis SDK to display balances. You'll create a server-side rendered native balance page and a NextJS API endpoint returning native and ERC-20 balances.

You can find the repository with the final code here: https://github.com/MoralisWeb3/demo-apps/tree/main/nextjs

668668

Native Balance Page

662662

The /api/balances API Endpoint Response

The Steps We Will Take

  1. Create a NextJS dapp
  2. Import and set up the latest Moralis JS SDK
  3. Integrate your application with Moralis services
  4. Read any blockchain data from any blockchain

Prerequisites

  1. Create a Moralis account
  2. Install and set up your editor of choice (we will use VSC in this tutorial)
  3. Install NodeJS

Create a NextJS Dapp

For this part of the tutorial, we will create a dapp that displays the native balance, ERC-20 tokens, and NFTs for any address and EVM chain!🚀

  1. Create a new folder for your project and open it in your editor
  2. Initialize a new project:
npm init

Give it a name and fill in the details as you want (press enter to use the default options). You should now have a package.json file that looks something like this:

{
  "name": "simple-nextjs-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
  1. Install the required dependencies:
npm install moralis next react react-dom
yarn add moralis next react react-dom
pnpm add moralis next react react-dom
  1. Open package.json and add the following scripts:
"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "lint": "next lint"
}
  1. Create a pages directory at the root of your application and add the index.jsx file with the following content:
function HomePage() {
  return <div>Welcome to my Next.js dApp!</div>
}

export default HomePage

📘

NextJS is built around the concept of pages. A page is a React component exported from a .js, .jsx, .ts, or .tsx file in the pages directory.

Add Moralis to Your NextJS Dapp

  1. Get your Web3 API key from the Moralis dashboard:
28802880

Admin Panel

  1. Create a .env.local file at the root and add a new environment variable, MORALIS_API_KEY; enter your API key as the value:
MORALIS_API_KEY=replace_me

📘

NextJS .env.local variables are accessible to the entire application and are never exposed to the browser. They are stored only on the server side, which makes them safe.

  1. After .env.local is added, you can start your app:
npm run dev

🚧

Every time you modify the .env.local file, you need to restart your app.

The Moralis SDK Inside getServerSideProps

You can use the Moralis SDK safely inside getServerSideProps from NextJS.

📘

getServerSideProps only run on the server side and never on the browser. When you request a page, getServerSideProps runs at request time, and this page will be pre-rendered with the returned props.

Server-Side Rendered Native Balance Page

Let's create a server-side rendered page for displaying a native balance:

  1. Create a new page file, native.jsx, for displaying the native balance:
function Native() {
    return <div>Native Balance</div>;
}

export default Native
  1. Add a getServerSideProps function:
// props are passed from getServerSideProps
function Native(props) {
    return <div>Native Balance</div>;
}

// This gets called on every page render
export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
} 

export default Native
  1. Update getServerSideProps to start the Moralis SDK and call the "native balance" endpoint:
import Moralis from 'moralis';
import { EvmChain } from '@moralisweb3/evm-utils';

function Native(props) {
    return <div>Native Balance</div>;
}

export async function getServerSideProps(context) {
    // reads the api key from .env.local and starts Moralis SDK
    await Moralis.start({ apiKey: process.env.MORALIS_API_KEY });

    const address = '0x...';

    const nativeBalance = await Moralis.EvmApi.balance.getNativeBalance({
        chain: EvmChain.ETHEREUM,
        address,
    });

    return {
        props: { 
            address,
            // Return the native balance formatted in ether via the .ether getter
            nativeBalance: nativeBalance.result.balance.ether 
        },
    };
}

export default Native
  1. Now, let's receive and use the props in our server-side rendered page:
import Moralis from 'moralis';
import { EvmChain } from '@moralisweb3/evm-utils';

function Native({ nativeBalance, address }) {
    return (
        <div>
            <h3>Wallet: {address}</h3>
            <h3>Native Balance: {nativeBalance} ETH</h3>
        </div>
    );
}

export async function getServerSideProps(context) {
    await Moralis.start({ apiKey: process.env.MORALIS_API_KEY });

    const address = '0x...';

    const nativeBalance = await Moralis.EvmApi.balance.getNativeBalance({
        chain: EvmChain.ETHEREUM,
        address,
    });

    return {
        props: { address, nativeBalance: nativeBalance.result.balance.ether },
    };
}

export default Native;
  1. Visit the <http://localhost:3000/native> page to see the results:
668668

The /api/balances API Endpoint Response

Moralis' SDK Inside the NextJS API

You can create a NextJS API and use the Moralis SDK safely inside.

📘

API routes provide a solution to build your API with NextJS.
Any file inside the pages/api folder is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side-only bundles and won't increase your client-side bundle size.

The NextJS API Returning User Balances

Let's create a NextJS endpoint that returns information about the user (native and ERC-20 balances):

  1. Create pages/api/balances.js with the following content:
import Moralis from 'moralis';
import { EvmChain } from '@moralisweb3/evm-utils';

export default async function handler(req, res) {
    // reads the api key from .env.local and starts Moralis SDK
    await Moralis.start({ apiKey: process.env.MORALIS_API_KEY });

    const address = '0x...';

    // Promise.all() for receiving data async from two endpoints
    const [nativeBalance, tokenBalances] = await Promise.all([
        Moralis.EvmApi.balance.getNativeBalance({
            chain: EvmChain.ETHEREUM,
            address,
        }),
        Moralis.EvmApi.token.getWalletTokenBalances({
            chain: EvmChain.ETHEREUM,
            address,
        }),
    ]);
    res.status(200).json({
        // formatting the output
        nativeBalance: nativeBalance.result.balance.ether,
        tokenBalances: tokenBalances.result.map((token) => token.display()),
    });
}
  1. To test your new API, you can open <http://localhost:3000/api/balances> in your browser or make a normal fetch() request. The output should be the following:
{
    "nativeBalance":"1883.468363260026992429",
    "tokenBalances":["3.0 USDT","1.42 yvUSDT"]
}

What’s Next

Now that you know the basics of NextJS and Web3 - let's build some full-stack dapps. See the examples below:

Did this page help you?