Search⌘ K

Connect to MetaMask

Explore how to connect your web application to MetaMask to access user accounts and send transactions to smart contracts. This lesson guides you through implementing connection flows using web3.js methods like requestAccounts and getAccounts, managing connection states with React, and improving user experience by handling account persistence and UI updates.

Before we can read blockchain data or send transactions to our smart contract, we need to connect our application to MetaMask. If this process succeeds, our application will be able to get the user’s account address and send transactions signed with the user’s private key to the Ethereum network.

This is exactly what we'll implement in this lesson, and this will be the last hurdle before we can access the Auction smart contract from the web application.

Connecting to MetaMask

The process of connecting to MetaMask is initiated by a web application. To initiate a connection flow, we need to call requestAccounts from the web3.js library:

Javascript (babel-node)
const accounts = await web3.eth.requestAccounts()

If our application is not yet connected to MetaMask and we call this method, MetaMask will display a window that asks a user if they want to connect our application to MetaMask. If they approve, our application will be able to get the user’s current account and then use our application.

Selecting an account to connect with MetaMask
Selecting an account to connect with MetaMask

If the user approves ...