Switch networks and add new networks to MetaMask.
Switch to a different Ethereum network
Prompts the user to switch to a different network. The network must already be added to MetaMask, or the user will get an error.
async function switchToSepolia() {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xaa36a7' }] // Sepolia
});
console.log('Switched to Sepolia');
} catch (error) {
if (error.code === 4902) {
console.error('Sepolia not added to MetaMask');
// Optionally add the network with wallet_addEthereumChain
} else {
console.error('Switch failed:', error);
}
}
}Predefined Networks (usually pre-added to MetaMask):
Add a new custom network to MetaMask
Adds a new blockchain network to MetaMask that the user can then connect to. Useful for L2s, private networks, or testnets not pre-configured.
async function addArbitrum() {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: '0xa4b1',
chainName: 'Arbitrum One',
rpcUrls: ['https://arb1.arbitrum.io/rpc'],
blockExplorerUrls: ['https://arbiscan.io/'],
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18
}
}]
});
console.log('Arbitrum added to MetaMask');
} catch (error) {
console.error('Add network failed:', error);
}
}Required Parameters:
async function ensureNetwork(chainId, networkConfig) {
try {
// Try to switch first
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId }]
});
} catch (error) {
// If network not found, add it
if (error.code === 4902) {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [networkConfig]
});
} catch (addError) {
console.error('Failed to add network:', addError);
}
} else {
console.error('Failed to switch network:', error);
}
}
}
// Usage
const arbitrumConfig = {
chainId: '0xa4b1',
chainName: 'Arbitrum One',
rpcUrls: ['https://arb1.arbitrum.io/rpc'],
blockExplorerUrls: ['https://arbiscan.io/'],
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18
}
};
await ensureNetwork('0xa4b1', arbitrumConfig);