Add a 'Connect Wallet' Button to Your Website - Next.js and RainbowKit Edition!

Add a 'Connect Wallet' Button to Your Website - Next.js and RainbowKit Edition!

Create a functional 'Connect Wallet' button on your website using Next.js along with RainbowKit

This article is part of my 'web 3' series where I share what I'm learning in #30DaysOfWeb3 - a 30-day online course by Women Build Web3!

If you are new to web 3 - my "Web 3 for Beginners" article was featured on Hashnode and may be a good starting point for you :)

Introduction

In my previous article, I shared with you a quick tutorial on how to make your 'Connect Wallet' button work using simple vanilla JavaScript.

Today, I am sharing with you a more advanced version using Next.js and RainbowKit!

This should work with any wallet that you have already installed in your browser, and is not intended to be for a particular wallet such as Metamask.

What is RainbowKit?

Screen Shot 2022-08-08 at 5.34.24 pm.png

RainbowKit is a React library that makes it easy to add a wallet connection to your website.

FROM THE RAINBOWKIT DOCS: "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!"

You can even tweak the RainbowKit UI to match your branding.

It utilizes the most commonly used libraries in the web3 ecosystem: ethers.js and Wagmi.

Ethers.js aims to be a "complete and compact library for interacting with the Ethereum Blockchain and its ecosystem".

Screen Shot 2022-08-08 at 5.35.14 pm.png

Wagmi is "a collection of React Hooks containing everything you need to start working with Ethereum".

Screen Shot 2022-08-08 at 5.36.05 pm.png

With RainbowKit, we will be using Wagmi to create the functionality of our Connect Wallet button.

Let's get started!

1) Next.js Setup

Create a Next.js boilerplate by typing the following in your terminal:

npx create-next-app@latest <your-app-name>
// or
yarn create next-app <your-app-name>
// or
pnpm create next-app <your-app-name>

2) Wagmi and RainbowKit Installation

Install RainbowKit and it's dependencies (Ethers and Wagmi) by typing this into your terminal:

npm install @rainbow-me/rainbowkit wagmi ethers

To learn more about RainbowKit installation, take a look at their docs.

3) Create a .env.local file to store a node provider key

To get a node provider key, you can sign up on websites such as Alchemy and Infura.

This step is not 100% essential for this tutorial, but it is helpful in later steps.

After grabbing your node provider key (for example, Alchemy key), create a new file in your root folder called .env.local.

This file is where you will keep your "secret" back-end web3 data so that it isn't visible on your front-end.

Add your node provider key in the .env.local file in this format:

NEXT_PUBLIC_ALCHEMY_ID=<Your Alchemy API Key>

4) Configure RainbowKit and Wagmi

a) Go to your _app.js file and add the following code to the top of the file:

import "@rainbow-me/rainbowkit/styles.css";
import { getDefaultWallets, RainbowKitProvider } from "@rainbow-me/rainbowkit";
import { chain, configureChains, createClient, WagmiConfig } from "wagmi";
import { alchemyProvider } from "wagmi/providers/alchemy";
import { publicProvider } from "wagmi/providers/public";

NOTE: We are using Alchemy in the above example. Be sure to edit the above code based on which Ethereum node provider your project is using.

b) Configure your chains and providers

Configure your desired chains to be used by Wagmi, and also the providers you want to use. Add this to your _app.js file.

const { chains, provider } = configureChains(
  [chain.polygon],
  [publicProvider()],
)

In the above code, we can see that signing up with a node provider is not 100% necessary for this exercise, as the configureChains method contains a publicProvider function already.

However, the Wagmi docs state:

It is not recommended to only pass publicProvider to configureChains as you will probably face rate-limiting on the public provider endpoints. It is recommended to also pass an Alchemy provider or Infura provider as well.

Given this, we will edit the above code so it includes our Alchemy Provider. We can bring in the environment variable that we stored in our .env.local file:

const alchemyId = process.env.NEXT_PUBLIC_ALCHEMY_ID;

const { chains, provider } = configureChains(
  [chain.polygon],
  [alchemyProvider({ alchemyId }), publicProvider()]
)

You can add multiple chains to the configureChains method - but in this example, we will just use the Polygon Chain.

c) Configure your connectors

Add the code below to your _app.js file to set up your connectors. We will use these connectors when setting up our wagmi client in the next step.

const { connectors } = getDefaultWallets({
  appName: "My New Website",
  chains,
});

d) Create a Wagmi Client instance

To do this, use the createClient method and pass the result from configureChains and connectors to it.

const wagmiClient = createClient({
  autoConnect: true,
  connectors,
  provider,
});

NOTE: By using autoConnect: true, the user only has to connect their wallet once, and they will stay logged in until they log out.

e) Wrap the application with the providers

In our _app.js file, we can now wrap our application with RainbowKitProvider and WagmiConfig, like this:

export default function MyApp({ Component, pageProps }) {
  return (
    <WagmiConfig client={wagmiClient}> // <----
      <RainbowKitProvider chains={chains}> // <----
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </RainbowKitProvider> // <----
    </WagmiConfig> // <----
  );
}

f) Additional information

While I have explained the above process step-by-step... there is also another easier way to get this all done for you...

...and that is with RainbowKit's boilerplate!

Use the following commands in your terminal:

npm init @rainbow-me/rainbowkit@latest
// or
yarn create @rainbow-me/rainbowkit@latest
// or
pnpm create @rainbow-me/rainbowkit@latest

This will prompt you for a project name, generate a new directory containing a boilerplate project, and install all required dependencies!

Pretty neat, huh?

Moving on...

5) Set up the Navbar.js file with your 'Connect Wallet' button

Create a Navbar.js file in your components folder.

a) Import RainbowKits ConnectButton component and Wagmis useAccount and useDisconnect hooks

We can use Wagmi hooks and RainbowKits ConnectButton component to:

  • Enable the user to connect their wallet
  • To inform the user that their wallet is connected

Add these imports to the top of your Navbar.js file:

import { ConnectButton } from "@rainbow-me/rainbowkit";
import { useAccount, useDisconnect } from "wagmi";

b) Add the Wagmi hooks to the Navbar.js component

Add these hooks directly below the start of the Navbar function, like this:

export default function Navbar() {
    const { data: account } = useAccount();
    const { disconnect } = useDisconnect();

The useAccount hook: To access the connected wallet if it exists.

The useDisconnect hook: To disconnect the currently connected wallet.

c) Render the button

If the user's wallet is connected, we will render a button in our UI that displays the user's wallet address.

If the user's wallet is not connected, we will render RainbowKits Connect Wallet button.

We can do this in our Navbar.js file using a conditional ternary operator:

<div>
  {account ? (<button><p>{account.address}</p></button>) : (<ConnectButton />)}
</div>

We can add this code wherever we would like the 'Connect Wallet' button to appear in our <Navbar> component!

RainbowKit will now handle your user's wallet selection, display wallet/transaction information and handle network/wallet switching. 戊

d) Dropdown menu attached to the Connect Wallet button

As an extra, if we would like to display a drop-down menu from this button when a user has their wallet connected, we could perhaps add a <Navmenu> component in place of the <p>{account.address}</p>.

We could then pass the account object and disconnect function to the <Navmenu> component and display <p>{account.address}</p> in the Navmenu component.

e) Add a button to disconnect the wallet

If we'd like users to be able to disconnect their wallet, we could add this to the dropdown menu in the <Navmenu> component:

<div>
   {({ account }) => (
      <a onClick={disconnect}>Log Out</a>
   )}
</div>

Throughout our website, we will conditionally render the UI by using Wagmi's useAccount hook based on the user's wallet connection.

Conclusion

Now you know two ways to make your 'Connect Wallet' button work!

If you have not seen my previous article yet - "Add a Connect Wallet button to Your Website - Vanilla JS Edition!" - then take a look!

I hope that you found this tutorial helpful.

Follow me on Twitter to see my progress with #30DaysOfWeb3!

Did you find this article valuable?

Support Hayley is Coding by becoming a sponsor. Any amount is appreciated!