The MetaMask API is a foundational tool for developers building decentralized applications (dApps) on the Ethereum blockchain and other EVM-compatible networks. By leveraging the window.ethereum provider injected into web pages, developers can create seamless Web3 experiences that allow users to authenticate, interact with blockchains, and sign transactions directly from their browsers.
This guide walks you through the core concepts, tools, and practical implementations of the MetaMask API, helping you integrate wallet functionality into your dApp with clarity and confidence.
Understanding the Ethereum Provider: window.ethereum
When a user installs MetaMask as a browser extension—on Chrome, Firefox, or Brave—the wallet injects a global JavaScript object called window.ethereum into every webpage. This object acts as a bridge between your dApp and the Ethereum network, enabling secure communication without exposing private keys.
This standardization comes from EIP-1193, which defines a unified interface for Ethereum providers across different wallets. Before this specification, each wallet implemented its own version of the provider API, leading to incompatibilities. Now, developers can rely on consistent behavior when interacting with MetaMask or other compliant wallets.
You can verify MetaMask’s presence in the browser using developer tools. Open the Sources tab and look under Page—if you see a cloud-like icon labeled "MetaMask," the extension is active and injecting the provider.
Once confirmed, you can interact directly with window.ethereum in the console. For example, to retrieve the current blockchain ID:
await window.ethereum.request({ method: 'eth_chainId' });
// Returns "0x1" if connected to Ethereum MainnetThe returned value is a hexadecimal string. To convert it to a readable number:
const chainIdHex = await window.ethereum.request({ method: 'eth_chainId' });
const chainIdNum = parseInt(chainIdHex, 16);
console.log(chainIdNum); // Outputs: 1👉 Discover how to connect your wallet securely using modern Web3 practices.
What Is JSON-RPC?
JSON-RPC is a lightweight, transport-agnostic protocol that uses JSON to encode remote procedure calls. It's the backbone of communication between dApps and blockchain nodes via providers like MetaMask.
Each request follows a simple structure:
method: The RPC method name (e.g.,eth_chainId)params: Optional parametersid: A unique identifier to match responses to requestsjsonrpc: Protocol version (always "2.0")
Example request:
{ "id": 1, "jsonrpc": "2.0", "method": "eth_chainId", "params": [] }Response:
{ "jsonrpc": "2.0", "result": "0x1", "id": 1 }This simplicity allows developers to interact with blockchains using familiar HTTP or WebSocket transports while maintaining cross-platform compatibility.
Common MetaMask API Methods
MetaMask supports a wide range of JSON-RPC methods, categorized mainly under eth_ and wallet_ prefixes.
Key Methods You Should Know
eth_accounts– Retrieves currently connected account addresses.eth_chainId– Returns the current chain ID in hexadecimal format.wallet_addEthereumChain(EIP-3085) – Requests adding a new network to the user’s wallet.wallet_switchEthereumChain(EIP-3326) – Prompts the user to switch to a specified chain.eth_sendTransaction– Initiates a transaction signed by the user.
These methods empower dApps to dynamically manage network connections and user interactions.
Handling Chain Switching and Network Addition
A common use case is switching users from one network (e.g., Ethereum) to another (e.g., Polygon). However, if the target chain isn’t already added to MetaMask, wallet_switchEthereumChain will fail.
To handle this gracefully, combine both methods in a try/catch block:
const switchToPolygon = async () => {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x89' }], // Polygon Mainnet
});
} catch (error) {
if (error.code === 4902) {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0x89',
chainName: 'Polygon Mainnet',
nativeCurrency: {
name: 'Matic',
symbol: 'MATIC',
decimals: 18,
},
rpcUrls: ['https://polygon-rpc.com/'],
blockExplorerUrls: ['https://polygonscan.com/'],
},
],
});
} catch (addError) {
console.error('Failed to add network:', addError);
}
}
}
};This pattern ensures smooth user experience regardless of whether the network exists in their wallet.
👉 Learn how to implement secure wallet connections in your dApp today.
Working with Smart Contracts
To interact with smart contracts—like minting an NFT—you need to send transactions through MetaMask. When a contract function is marked payable, users must approve both the transaction and the associated cost.
Example Solidity function:
function mint(uint256 tokenId) public payable {
require(totalSupply < maxSupply, "Max supply reached");
tokenOwners[tokenId] = msg.sender;
totalSupply++;
}Frontend integration using ethers.js:
const mintNFT = async () => {
try {
const tx = await contract.mint(tokenId, { value: priceInWei });
await tx.wait();
console.log("NFT minted successfully!");
} catch (error) {
console.error("Minting failed:", error);
}
};This triggers MetaMask’s signature request modal, allowing users to review gas fees and confirm the transaction.
Essential Tools for Development
1. MetaMask Ethereum Provider Docs
Official documentation detailing all available methods: Ethereum Provider API
2. MetaMask RPC API Reference
Comprehensive list of supported RPC methods: RPC API Guide
3. MetaMask API Playground
Interactive environment to test API calls directly in-browser: API Playground
4. Chainlist.org
A curated database of EVM-compatible networks with correct RPC settings and metadata: Chainlist
5. Eserialize.com
Tool for converting between hexadecimal and decimal values, useful for validating chain IDs and balances.
Frequently Asked Questions
Q: How do I detect if MetaMask is installed?
A: Check for the existence of window.ethereum:
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is available');
}Q: What does error code 4902 mean?
A: It indicates that the requested chain is not added to the user’s wallet. Use wallet_addEthereumChain to resolve it.
Q: Can I call MetaMask functions without user interaction?
A: No—security restrictions require user approval for actions like account access or transaction signing.
Q: Is the MetaMask API compatible with mobile apps?
A: Yes—MetaMask Mobile supports the same window.ethereum interface via in-app browsers.
Q: How do I handle disconnections or account changes?
A: Listen for events:
window.ethereum.on('accountsChanged', (accounts) => {
// Update UI with new account
});
window.ethereum.on('chainChanged', (chainId) => {
// Reload or adjust network context
});Q: Should I use MetaMask SDK instead?
A: The SDK simplifies integration for mobile and deep linking but builds on top of the same underlying API. Use it if you need cross-platform support.
👉 Explore advanced Web3 integrations with step-by-step guides and examples.
Core Keywords
MetaMask API, Ethereum provider, JSON-RPC, wallet integration, dApp development, blockchain interaction, smart contract calling, Web3 authentication
By mastering these fundamentals, you’ll be well-equipped to build intuitive, secure, and interoperable Web3 applications that deliver real value to users.