Query which blockchain network the user is connected to.
Get the current chain ID
Returns the chain ID of the network the user is currently connected to. Different networks have different IDs.
async function getCurrentChain() {
const chainId = await window.ethereum.request({
method: 'eth_chainId'
});
console.log('Chain ID:', chainId); // e.g., '0x1' for Mainnet
// Map to network name
const networks = {
'0x1': 'Ethereum Mainnet',
'0xaa36a7': 'Sepolia Testnet',
'0x89': 'Polygon',
'0xa4b1': 'Arbitrum',
};
const networkName = networks[chainId] || 'Unknown Network';
console.log('Network:', networkName);
return { chainId, networkName };
}Common Chain IDs:
Get the network version (legacy method)
Similar to eth_chainId but returns a string. This is the older standard method. Prefer eth_chainId for new code.
async function getNetworkVersion() {
const version = await window.ethereum.request({
method: 'net_version'
});
console.log('Network version:', version);
// Returns: '1' (Mainnet), '11155111' (Sepolia), etc.
}Users can switch networks in MetaMask. Listen for changes to keep your app in sync:
// Listen for network changes
window.ethereum.on('chainChanged', (chainId) => {
console.log('User switched to chain:', chainId);
// Reload page or update UI
window.location.reload();
});