I would like to have a button that switches between main net and ropsten on my app, in order to do so I need to programatically change the current network with MetaMask. But I cannot find aby reference about this. Do you guys have any idea on how to achieve this?

  • I saw some modern apps that cause metamask to open a dialogue in Metamask asking for permission to change to a specific network. Anyone knows how to do this? Sep 18, 2021 at 2:45

1 Answer 1


You will need to prompt the users to change their network via MetaMask.

Assuming web3 is an initialised instance of the Web3 library with a provider:

import Web3 from "web3";


const getWeb3 = () => {
    return new Promise((resolve, reject) => {
        // Wait for loading completion to avoid race conditions with web3 injection timing.
        window.addEventListener("load", async () => {
            // Modern dapp browsers...
            if (window.ethereum) {
                const web3 = new Web3(window.ethereum);
                try {
                    // Request account access if needed
                    await window.ethereum.enable();
                    // Acccounts now exposed
                } catch (error) {
           // Legacy dapp browsers...
           else if (window.web3) {
               // Use Mist/MetaMask's provider.
               const web3 = window.web3;
               console.log("Injected web3 detected.");
           // Fallback to localhost; use dev console port by default...
           else {
               const provider = new Web3.providers.HttpProvider(
               const web3 = new Web3(provider);
               console.log("No web3 instance injected, using Infura/Local web3.");

const detectEthereumNetwork = async () => {
    const web3 = await getWeb3();
    web3.eth.net.getNetworkType().then(async (netId) => {
        // Do something based on which network ID the user is connected to

  • 1
    so where exactly did you do the prompting
    – JSking
    Sep 29, 2021 at 8:51
  • It would be done where the "// Do something based on which network ID the user is connected to" comment is, based on the network ID. But this code is quite dated now, I'd recommend using something like github.com/EthWorks/useDApp nowadays
    – Jay
    Sep 30, 2021 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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