Adding a custom network to MetaMask allows users to interact with different blockchain networks beyond Ethereum. This guide will walk you through the steps to add a custom network programmatically using JavaScript.

Checking for MetaMask Installation

Before adding a custom network, ensure that the MetaMask extension is installed in the user's browser. You can check for its presence by accessing the ethereum object.


if (typeof window.ethereum !== 'undefined') {
console.log("MetaMask is installed");
} else {
console.log("MetaMask is not installed");
}

Adding a Custom Network

To add a custom network, use the request method of the ethereum object with the wallet_addEthereumChain method. Below is an example of how to add the Polygon (Matic) network.


async function addMaticNetwork() {
try {
const result = await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [{
chainId: "0x89",
rpcUrls: ["https://polygon-rpc.com/"],
chainName: "Matic Mainnet",
nativeCurrency: {
name: "MATIC",
symbol: "MATIC",
decimals: 18
},
blockExplorerUrls: ["https://polygonscan.com/"]
}]
});
console.log("Network added successfully:", result);
} catch (error) {
console.error("Error adding network:", error);
}
}

Important Considerations

  • User Consent: Always ensure that the request to add a network is made in response to a user action, such as clicking a button. This respects user consent and awareness.
  • Error Handling: Implement error handling to manage any issues that may arise during the network addition process.
  • Testing: Test the functionality thoroughly to ensure a smooth user experience when adding custom networks.

Conclusion

By following the steps outlined in this guide, you can programmatically add custom networks to MetaMask, enhancing the user experience of your decentralized applications (DApps). This functionality simplifies the onboarding process for users, allowing them to interact with various blockchain networks seamlessly.