patternjavascriptMajor
ethers.js v6: provider and signer initialization with BrowserProvider
Viewed 0 times
ethers.js v6.x
ethers v6BrowserProviderWeb3ProvidergetSignerMetaMaskwallet
Problem
ethers.js v6 removed the Web3Provider class and changed how you obtain a provider and signer from a browser wallet like MetaMask.
Solution
Use BrowserProvider instead of Web3Provider. Call provider.getSigner() which now returns a Promise. Example:
import { BrowserProvider } from 'ethers';
const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();Why
ethers.js v6 was a major rewrite with breaking API changes. BrowserProvider wraps EIP-1193 providers (like MetaMask's window.ethereum) and returns ethers-compatible objects.
Gotchas
- getSigner() is now async — always await it
- window.ethereum may be undefined if no wallet is installed; guard with a check
- Multiple wallets injecting window.ethereum can cause conflicts; use EIP-6963 for multi-wallet support
Code Snippets
Initialize provider and signer in ethers.js v6
import { BrowserProvider } from 'ethers';
async function connectWallet() {
if (!window.ethereum) throw new Error('No wallet found');
const provider = new BrowserProvider(window.ethereum);
await provider.send('eth_requestAccounts', []);
const signer = await provider.getSigner();
const address = await signer.getAddress();
return { provider, signer, address };
}Context
Migrating from ethers.js v5 to v6, or initializing a wallet connection in a dApp frontend
Revisions (0)
No revisions yet.