How to connect nextJS application to a test blockchain?

Mark
Coinmonks
9 min readApr 30, 2024

--

Connecting to BuildBear cloud

Learn the ins and outs of testing decentralized applications on BuildBear’s cloud infrastructure while unlocking the potential of blockchain technology. In our latest article, we dive deep into connecting web3 applications to custom blockchain networks using RainbowKit, Wagmi, and Viem within a Next.js framework. Learn how to seamlessly integrate crypto wallets, streamline testing processes, and explore the potential of BuildBear’s cloud infrastructure. Don’t miss out — read it now!

Introduction

This material is a continuation of the work done within the article

Let remind you that within that item, we explored the challenges of testing decentralized applications (DApps) on blockchain platforms and introduced BuildBear as a solution. We discussed the complexities involved in interacting with blockchain networks, managing data, smart contracts, and test wallets. BuildBear offers streamlined solutions such as fast cloud Sandbox creation, scalable resources, and easy test wallet management. With an intuitive interface and free access, BuildBear simplifies the testing process for developers.

During this article we will use the results of the settings made the last time and see how easy it is to connect your web3 application frontend to work with a test private blockchain network.

Before we begin, let’s take a look at the building primitives we’re going to use.

This example will use the following technology stack.

TypeScript — is a free and open-source high-level programming language developed by Microsoft that adds static typing with optional type annotations to JavaScript. TypeScript is a language extension that adds features to ECMAScript 6. It helps developers to make code more readable and maintainable.

ReactJS — is an open-source front-end JavaScript library for building user interfaces based on components. It is maintained by Meta (formerly Facebook) and a community of individual developers and companies. Currently, according to the official documentation, it is not recommended to start new projects on pure React.js without React-powered frameworks.

NextJS — is an open-source a flexible framework on a top of ReactJS with server-side rendering and static website generation. Official React documentation mentions Next.js as the first among “Recommended frameworks”

Wagmi — is a library, consisting of a collection of 40+ React Hooks. It provides developers with intuitive building blocks to build their web3 ReactJS apps and significantly simplifies implementation of app logic related with typical operations with wallets, transactions, smart-contracts, etc.

Viem — is full-featured lightweight library for interacting with EVM chains. It is a TypeScript Interface that provides low-level stateless primitives for interacting with EVM-based blockchains. It is an alternative to ethers.js and web3.js with a focus on reliability, efficiency, and excellent developer experience.

RainbowKit — is a React library that makes it easy to add wallet connection to your dApp. Aside from handling the connection and disconnection of wallets, RainbowKit supports numerous wallets, swaps connection chains, resolves address to ENS, displays balance and much more!

Great! Let’s get started. First, let’s create a skeleton of our application based on NextJS. To do this you need to run the command:

npx create-next-app@latest

This starts installer.

We don’t need ESLint, TailwindCSS for this example. So disable them for this example. This is how you need to answer the installer’s questions:

After creating the application skeleton, go to the folder of the created project:

cd nextjsweb3app

And launch the application:

npm run dev

If you open the link http://localhost:3000/ in the browser, the default nextJS welcome page should be displayed.

Now let’s clean up a bit of the code that created the installation package for us.

To do this, go-ahead, following the recommendations on the main page to edit the file app/page.tsx. You should remove everything inside the Home function so that the Home function returns the following content:

export default function Home() {
return (
<main className={styles.main}>
<div className={styles.center}>
NextJS Web3 application
</div>
</main>
);

Build a project for just in case and check that these edits did not break anything…

Next we need to install the rainbowkit/wagmi/viem packages.

To do this, go to the RainbowKit website https://www.rainbowkit.com/docs/installation and in the Manual Installation section, copy the installation command:

npm install @rainbow-me/rainbowkit wagmi viem @tanstack/react-query

Please note that RainbowKit has a command to create a project from scratch based on its own application template, but it seems that a more frequent and relevant case is when rainbowkit/wagmi/viem is connected to an existing project. Therefore, we will not use this option.

It is also worth noting that React/nodeJS are known for their regular issues with installing libraries due to dependency version conflicts. Since we are working with several frameworks at once (nextJS, rainbowkit, wagmi..) that use the same dependent libraries, there is a high probability that some version conflict may appear, so it is recommended to install with the legacy-peer-deps flag. And that’s exactly why a certain version of RainbowKit is used for this example. The RainbowKit API changes quite dynamically and, for other versions, the code presented here may simply not be compiled. You can try it in respect of your own curious.

Execute the command to install the libraries rainbowkit/wagmi/viem in the project’s folder:

npm install @rainbow-me/rainbowkit@2.0.5 wagmi viem@2.x @tanstack/react-query --legacy-peer-deps.

Before you start changing the code, you need to follow the recommendations from here https://github.com/rainbow-me/rainbowkit/blob/main/examples/with-next-app/next.config.js, and change next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
webpack: config => {
config.externals.push('pino-pretty', 'lokijs', 'encoding');
return config;
},
};

export default nextConfig;

Now, after the necessary libraries are installed, we can proceed to writing the code that connects the crypto-wallet to our nextJS application.

In the app/page.tsx file, you MUST specify that this is client code and rendering must occur in the browser (by default, NextJS component rendering occurs on the server):

'use client'

After that, add the dependencies we need:

import '@rainbow-me/rainbowkit/styles.css';

import {
WalletList,
RainbowKitProvider,
getDefaultConfig,
Chain,
ConnectButton,
} from '@rainbow-me/rainbowkit';


import { metaMaskWallet, trustWallet, uniswapWallet, walletConnectWallet } from '@rainbow-me/rainbowkit/wallets';
import { WagmiProvider } from 'wagmi';
import {
polygon,
polygonAmoy,
} from 'wagmi/chains';

import { QueryClientProvider, QueryClient, } from "@tanstack/react-query";

Define a client object to be passed to the QueryClientProvider component:

const queryClient = new QueryClient();

Now let’s define the parameters of our private test blockchain network in the configuration in order to work with this network in our web3 application. This can be done by simply copying them from Dashboad BuildBear. For this, return to the Dashboad page of our private Cloud Sandbox on BuildBear.io, created in the last article, click on the “</> Snippets” button, select the Wagmi section and copy the contents:

Paste the code into the page.tsx file

The only thing that is not required is this block of code, which BuildBear generates by default (at least at the time of writing this instruction):

const { chains, publicClient, webSocketPublicClient } = configureChains(
[bbtestnet],
[
jsonRpcProvider({
rpc: (chain) => (
http: "https://rpc.buildbear.io/mushy-quicksilver-xxxxxxxx",
}),
}),
]
);

It needs to be removed. Most likely the thing is that the rainbowkit/wagmi/viem library is developing too fast and, most likely, BuildBear simply did not catch up to adjust the template yet.

We are going also slightly improve the visual presentation of our custom network in the crypto wallet by adding an icon:

const bbtestnet = {
id: 16898,
name: "mushy-quicksilver-хххххххх",
//network: "bbtestnet", !!! it is not needed
iconUrl: 'https://blockchainmetrics.online/img/block-chain.svg', // add network icon
iconBackground: '#fff', // add icon background


}

Next, we will define a list of crypto wallets that we will support in our web3 application:

const _walletList: WalletList = [
{
groupName: 'Recommended',
wallets: [metaMaskWallet, trustWallet, uniswapWallet, walletConnectWallet],
},
];

Let’s set a list of blockchain networks that our web3 application will support. For now it will be a set of our test network, Polygon Mainnet and Polygon Amoy test chain:

const _chains: readonly [Chain, ...Chain[]] = [bbtestnet, polygon, polygonAmoy,];

After this, let’s create a configuration object for Wagmi:

const config = getDefaultConfig({
appName: 'nexnjsweb3app',
projectId: 'YOUR_PROJECT_ID',
wallets: _walletList,
chains: _chains,
ssr: false,
});

Now all that remains is to add to the home page of our application crypto wallet connect button. To do this, change the Home function in the app/page.tsx file as follows:

export default function Home() {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider>
<main className={styles.main}>
<div className={styles.center}>
<ConnectButton />
</div>
</main>
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
);
}

That’s all. Now build and start the project again.

Please note that when selecting a network, our test private blockchain is displayed with the icon we specified in the configuration:

Confirm in Metamask the connection of the local application and changing the network to our test network and, as a result, you should see something like the following on the home page of our test NextJS web3 application:

Congratulations!

We have just made a web3 application, connecting it to the blockchain, from a regular nextJS application in a few lines of code. Your personal test cloud blockchain, forked from Polygon mainnet, created previously, is used as the blockchain. Isn’t it all very easy and fast? Absolutely nothing complicated. The only piece where you can lose a lot of time when connecting a crypto-wallet to your nextJS application using RainbowKit is dealing with node package dependencies, that is, due to various errors caused by version conflicts.

But that’s not all. The resulting code is intended only to demonstrate the necessary code and settings necessary to connect rainbowkit/wagmi/viem to a nextJS application and, therefore, the resulting test application is not very correct from the point of view of the recommended layout of nextJS components. In the next articles in this series about testing web3 applications on the BuildBear cloud infrastructure, we will reorganize our code and work out the following issues:

  • how to get the wallet balance in native tokens,
  • how to get the wallet balance for a given ERC20 token,
  • how to transfer ERC20 tokens from one wallet to another.

And all these manipulations with wallets will occur from the web3 nextJS application on your cloud private blockchain network. You will be able to see the transaction results for your network directly in the BuildBear block explorer;

The code for this project is available here on GitHub:

Conclusion

In this article, we explored the process of connecting a web3 application frontend to a test private blockchain network using RainbowKit, Wagmi, and Viem within a Next.js application. We began by setting up a Next.js project and installing necessary libraries, focusing on RainbowKit, Wagmi, and Viem.

We demonstrated how to configure RainbowKit to connect to a custom blockchain network, leveraging settings from a BuildBear Cloud Sandbox. By integrating RainbowKit’s wallet connection features, we enabled users to connect their preferred crypto wallets to the web3 application easily.

Our example project showcased a basic implementation, but we acknowledged its limitations in terms of code structure and functionality. Future articles in this series will delve deeper into optimizing the codebase and implementing additional features. We plan to cover retrieving wallet balances, handling ERC20 tokens, and facilitating token transfers between wallets, all within the context of our web3 Next.js application running on a private blockchain network.

The project code is available on GitHub for reference and further exploration.

If you are interested in this topic, let’s keep exploring together.

Please, subscribe me.

Follow my X

--

--