Start a Web3 app on Next.js

A step-by-step guide to setup a Next.js web application, connect wallet and browse wallet's assets.

Next.js is a web development framework built on top of Node.js enabling React-based web applications functionalities such as server-side rendering and generating static websites.

Next.js and Mesh are JavaScript libraries, and so we will assume that you have some familiarity with HTML and JavaScript language, but you should be able to follow along even if you are coming from a different programming language. If you don't feel very confident, we recommend going through this JS tutorial, or the MDN JavaScript Reference or my preferred method, by watch a few videos from YouTube.

System setup

1. Visual Studio Code

Visual Studio Code is a code editor made by Microsoft. Download and install Visual Studio Code for code editing.

2. Node.js

Node.js is a cross-platform JavaScript runtime environment that runs on the V8 engine and executes JavaScript code. Install the Long-Term Support (LTS) version of Node.js (as of writing v16.16.0).

Setup Next.js

1. Create project folder and open Visual Studio Code

Create a new folder for your project, and give the folder a meaningful name. Open the Visual Studio Code application and drag your project folder into Visual Studio Code.

2. Create Next.js app

From the menu options in on your Visual Studio Code, open the Terminal and execute this command to create a new NextJs application:

npx create-next-app@latest --typescript .

3. Start development server

After the installation is complete, start the development server with:

npm run dev

Visit http://localhost:3000 to view your application. CTRL+C to stop the application.

Setup Mesh

1. Install MeshJS package

Install the latest version of Mesh with npm:

npm install @meshsdk/core @meshsdk/react

2. Add webpack in next.config.js

Open next.config.js and append webpack configurations. Your next.config.js should look like this:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: function (config, options) {
    config.experiments = {
      asyncWebAssembly: true,
      layers: true,
    };
    return config;
  },
};
module.exports = nextConfig;

In the more recent Next version, configuration for next.config.mjs:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: function (config, options) {
    config.experiments = {
      asyncWebAssembly: true,
      layers: true,
    };
    return config;
  },
};

export default nextConfig;

3. Congratulations

You just saved a few weeks of learning and a number days trying to get started. Your Next.js application is ready to connect wallet, browse assets and make some transactions.

See it in action

1. Add MeshProvider

React context is an essential tool for building web applications. It allow you to easily share state in your applications, so you can use the data in any component within the app. This means that when the user has connected their wallet, visiting different pages on the app ensure their wallet is still connected.

Open pages/_app.tsx, import and include MeshProvider. Your _app.tsx should look similar to this:

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { MeshProvider } from "@meshsdk/react";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <MeshProvider>
      <Component {...pageProps} />
    </MeshProvider>
  );
}

export default MyApp;

2. Add connect wallet component and check wallet's assets

Lets add the connect wallet component to allow users to connect wallets they have installed on their device. Connecting to wallets will ask the user for permission if not granted, and proceed to connect the selected wallet.

Lastly, we link those components together, allowing users to choose a wallet to connect, and query for assets in the wallet with wallet.getAssets().

Open pages/index.tsx and replace it with the following codes:

import { useState } from "react";
import type { NextPage } from "next";
import { useWallet } from '@meshsdk/react';
import { CardanoWallet } from '@meshsdk/react';

const Home: NextPage = () => {
  const { connected, wallet } = useWallet();
  const [assets, setAssets] = useState<null | any>(null);
  const [loading, setLoading] = useState<boolean>(false);

  async function getAssets() {
    if (wallet) {
      setLoading(true);
      const _assets = await wallet.getAssets();
      setAssets(_assets);
      setLoading(false);
    }
  }

  return (
    <div>
      <h1>Connect Wallet</h1>
      <CardanoWallet />
      {connected && (
        <>
          <h1>Get Wallet Assets</h1>
          {assets ? (
            <pre>
              <code className="language-js">
                {JSON.stringify(assets, null, 2)}
              </code>
            </pre>
          ) : (
            <button
              type="button"
              onClick={() => getAssets()}
              disabled={loading}
              style={{
                margin: "8px",
                backgroundColor: loading ? "orange" : "grey",
              }}
            >
              Get Wallet Assets
            </button>
          )}
        </>
      )}
    </div>
  );
};

export default Home;

Start the development server and try it:

npm run dev

Visit http://localhost:3000 to connect available wallets and view the assets in wallet.

If you are new to Cardano, you will first have to download one of the Cardano wallets. Tall Nupinks has written a detailed Cardano Wallets 101 guide to help you understand the fundamentals of a Cardano wallet, including its features and how it works. With this guide, you will be able to make an informed decision on the best Cardano wallet for your needs.

3. Try on your own

Implement another component to display wallet's address and the amount of lovelace in your Next.js application. Check out the wallet page for more details.