According to the MetaMask docs the recommended way to access the web3 is by creating a new instance of the Web3 class by passing the window.web3.currentProvider, which is injected by the MetaMask extension, to it's constructor:

const Web3 = require('web3');

const web3 = new Web3(window.web3.currentProvider);

However, when instantiated this way, the web3.eth.defaultAccount property is null and when I change accounts in the extension, the current account is not reflected in the Web3 instance.

On contrary, when I use the Web3 instance, which is injected directly, it works perfectly fine. I can access the web3.eth.defaultAccount right away and it's updated dynamically when I change current account in the extension:

const web3 = window.web3;

Why is that and how do I implement the correct integration with MetaMask?

  • MetaMask version: 3.12.1
  • web3 version: 0.19.0

2 Answers 2


Try web3.eth.accounts[0].

Or async, web3.eth.getAccounts(_accounts => selectedAccount = _accounts[0]). This will save the currently selected Metamask account to selectedAccount


you can use the following code to get an instance of web3.

import Web3 from "web3";

const getWeb3 = async () => {
  let web3Instance;
  let accounts;

  if (window.ethereum) {
    web3Instance = new Web3(window.ethereum);
    try {
      accounts= await window.ethereum.request({
        method: "eth_requestAccounts",
      console.log("accounts: ", accounts);
    } catch (error) {
      console.error("User denied account access");
      throw new Error("User denied account access");
  } else if (window.web3) {
    web3Instance = new Web3(window.web3.currentProvider);
  } else {
    console.error("No web3 instance found, please install MetaMask");
    throw new Error("No web3 instance found, please install MetaMask");

  return { web3Instance, accounts };

export default getWeb3;

After that you can use:

const {web3Instance} = await getWeb3();
const accounts = await web3Instance.eth.getAccounts();

to get the account. or, use the following to get the account:

const {account} = await getWeb3();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.