How to Connect Web3.js to MetaMask in 2023

As of Q1 2020, MetaMask has officially stopped injecting Web3.js, and has updated the way you access the current provider. Here’s how to make sure your dApp doesn’t break, and how to make it more compatible with the rest of the ecosystem.
The New, More Compatible Way
According to this article:
The primary motivation for these changes is to implement EIP-1102 and EIP-1193. This is great for everyone in the dApp community, since now Ethereum providers like MetaMask, Status, and Ethereum-compatible browsers will all have a standard to conform to for exposing their APIs.
The gist of the changes is basically that providers
like MetaMask and Status must continue to inject window.ethereum
, but now the window.ethereum
object itself is a provider
type that supports the methods defined in EIP-1102 and EIP-1193. No more having to check window.web3
for its currentProvider
— we can simply use window.ethereum
as the provider
itself!
The code:
const Web3 = require("web3");const ethEnabled = async () => { if (window.ethereum) { await window.ethereum.request({method: 'eth_requestAccounts'}); window.web3 = new Web3(window.ethereum); return true; } return false;}
Super clean! Essentially, we check if window.ethereum
exists, then create a window.web3
object with our own version of web3, using the window.ethereum
object as the input provider
.
In this case, the await window.ethereum.send({method: 'eth_requestAccounts'})
function calls the pop-up UI dialogue that asks the user’s permission to connect the dApp to MetaMask.
In this case, your dApp is now compatible with any EIP-1102 and EIP-1193 compliant Ethereum provider, making it accessible to many more potential users, and doesn’t lock your dApp into one provider.
If you enjoyed this article, I’d really appreciate if you check out a new tool I’m working on that allows you to easily distribute software, including NPM packages and wallet firmware, using Ethereum, IPFS, and Filecoin with a new open source tool, Valist — sign up for the beta at Valist.io!
We also have an awesome community of web3 and security engineers, come join our Discord server and hang out with us!