How to connect wallet to dApp with Next.js on Polkadot
Tags: polkadot, web3, nextjs, dapp
Published: 2023-05-01 01:53:43

## Overview
In decentralized applications, before a user gets to interact with the functionalities of an application, the user needs to connect the wallet address to the dApp to store the user's signature in the application. 
In this tutorial, we will be using a package called polkadot extension dapp for connecting the wallet to the dapp.

## Prerequisite
 This is a quick guide and there won't be any CSS in the guide. So to follow up this tutorial, you need to

- have [node.js](https://nodejs.org/en/download) installed or  [nvm](https://github.com/nvm-sh/nvm)
- have a basic knowledge on [next.js](https://nextjs.org/)

## Let's get started...
- Open up your terminal and initialize a new next.js project using the command `yarn create next-app` 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypkdpf6lhvsuy0bbmnln.png)
Make sure to opt for the options in the image above

- In your terminal, navigate into your newly created project and open it up in your code editor.

- In your code editor, open up the index.tsx file, clear the codes in there and open the code below into it

```
export default function Home() {
  return (
    <>
      <h2>Hey Polki, Welcome to Polkadot </h2>
      <button>Connect wallet</button>
    </>
  )
}

```

- In your terminal, run the command `yarn run dev` and you will get an output like the image below

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vg7dbxmzm1lfiz9m1yj0.png)

- In your browser, navigate to [localhost](http://localhost:3000/) and you will see the output of the page like the image below

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94ls04gg9jqpuw32rj11.png)

## Integrate the dapp connect wallet functionality

- Head over to [polkadot-extension](https://polkadot.js.org/extension/) and then [Talisman](https://chrome.google.com/webstore/detail/talisman-polkadot-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld), install these wallet extensions for polkadot and create an account.

- Next up in your terminal, we will be installing these packages
`yarn add @polkadot/extension-dapp @polkadot/extension-inject` and follow up this link [polkadot-extension-dapp](https://polkadot.js.org/docs/extension) to know more about it. 
After installation is complete,you should see an output like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dx087sp5bdlu6fpu18fa.png)

- We will be using dynamic import for the newly installed package. You can read more on dynamic imports here [dynamic-import](https://nextjs.org/docs/advanced-features/dynamic-import)
- In your index.tsx file, add the following import and lines to your code

```
import { useState } from 'react';
import dynamic from 'next/dynamic'

const web3Accounts = dynamic(() => import('@polkadot/extension-dapp'), { ssr: false });
const web3Enable = dynamic(() => import('@polkadot/extension-dapp'), { ssr: false });

```

- Let's create some states in our dapp and since we are using typescript, we need to add up types to our state using the inject extension that we installed. So add the following lines below to your code

```
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types'; 

...

const [account, setAccount] = useState<InjectedAccountWithMeta[]>([]);
const [selectedAccount, setSelectedAccount] = useState<InjectedAccountWithMeta>();
```

- So far, all the codes in our index.tsx file should look like this

```

import { useState } from 'react';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import dynamic from 'next/dynamic'

const web3Accounts = dynamic(() => import('@polkadot/extension-dapp'), { ssr: false });
const web3Enable = dynamic(() => import('@polkadot/extension-dapp'), { ssr: false });



export default function Home() {
  const [account, setAccount] = useState<InjectedAccountWithMeta[]>([]);
  const [selectedAccount, setSelectedAccount] = useState<InjectedAccountWithMeta>();
  return (
    <>
      <h2>Hey Polki, Welcome to Polkadot </h2>
      <button>Connect wallet</button>
    </>
  )
}

```

- Next up in index.tsx file, we will create an asynchronous function which will handle the functionality of the wallet connection on your dapp. 
Copy and paste these lines of codes below

```
async function connectWallet(){
    const { web3Enable,web3Accounts } = await import("@polkadot/extension-dapp");
    const extensions = web3Enable("Polki");
    
    if(!extensions) {
      throw Error("No Extension Found");
    }

    const allAccounts = await web3Accounts();

    console.log(allAccounts);

    if(allAccounts.length === 1){
      setSelectedAccount(allAccounts[0]);
    }
  }
```

- Finally add these last piece of codes below the return fragment

```
      {
        account.length === 0 ? <button onClick={connectWallet}>Connect Wallet</button> : null
      }
      
      {
        selectedAccount ? selectedAccount.address : null
      }
```

- All your codes should now look like this

```

import { useState } from 'react';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import dynamic from 'next/dynamic'

const web3Accounts = dynamic(() => import('@polkadot/extension-dapp'), { ssr: false });
const web3Enable = dynamic(() => import('@polkadot/extension-dapp'), { ssr: false });



export default function Home() {
  const [account, setAccount] = useState<InjectedAccountWithMeta[]>([]);
  const [selectedAccount, setSelectedAccount] = useState<InjectedAccountWithMeta>();

  async function connectWallet(){
    const { web3Enable,web3Accounts } = await import("@polkadot/extension-dapp");
    const extensions = web3Enable("Polki");
    
    if(!extensions) {
      throw Error("No Extension Found");
    }

    const allAccounts = await web3Accounts();

    console.log(allAccounts);

    if(allAccounts.length === 1){
      setSelectedAccount(allAccounts[0]);
    }
  }
  return (
    <>
      <h2>Hey Polki, Welcome to Polkadot </h2>
      {
        account.length === 0 ? <button onClick={connectWallet}>Connect Wallet</button> : null
      }
      
      {
        selectedAccount ? selectedAccount.address : null
      }
    </>
  )
}

```

- Make sure your terminal is still running and head over to the browser. Click on connect wallet button and you will get a pop up from your polkadot extension, requesting for permission to connect to your dapp. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzzqj0tp2rptep3ie5rk.png)

- Click on yes to grant it permission and viola, there you go, your wallet address connected to your dapp.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6crcc0a6j90h9un7ma4y.png)

- I hope you enjoyed this tutorial and learned something from it. This is just to show how the connect button works and you can use this as a guide whenever you are trying to add that functionality in your Next.js project. Go and build your web3 applications on Polkadot. Cheers