Ethers.js: MetaMask Client-Side Connection Guide
Ethers.js is a foundational JavaScript library for interacting with the Ethereum blockchain and its ecosystem. It provides a concise yet powerful interface for connecting to Ethereum nodes through providers like JSON-RPC, Infura, Etherscan, Alchemy, Cloudflare, or MetaMask.
This guide focuses on client-side dApp integration with MetaMask, targeting experienced front-end developers who want to wire up wallet connectivity and blockchain queries without unnecessary boilerplate.
MetaMask Connection Flow
MetaMask injects the window.ethereum
object into the browser context. Your dApp interacts with this object through Ethers.js by wrapping it in a Web3Provider
.
Minimal HTML Setup
MetaMask requires a browser context; direct file execution (file:///...
) won’t work. You’ll need to serve your page (e.g., with VS Code Live Server).
ether.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ethers.js + MetaMask</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.min.js"></script>
<script>
(async () => {
if (!window.ethereum) {
console.error("MetaMask not detected");
return;
}
// 1. Provider from injected Ethereum object
const provider = new ethers.providers.Web3Provider(window.ethereum);
// 2. Request account access (triggers MetaMask prompt)
await provider.send("eth_requestAccounts", []);
// 3. Differentiate: provider vs signer
const signer = provider.getSigner();
// 4. Example: fetch data
const blockNumber = await provider.getBlockNumber();
console.log("Current block:", blockNumber);
// 5. Example: active account
const address = await signer.getAddress();
console.log("Connected account:", address);
})();
</script>
</body>
</html>
Key Concepts
Provider → read-only blockchain access (e.g., block number, balance, contract state).
Signer → account-specific, signs transactions/messages, required for state-changing ops.
Testing
Serve with Live Server (VS Code) or any HTTP server.
Load the page in a MetaMask-enabled browser.
Approve the connection prompt.
Inspect the console for current block number and connected address.
Top comments (0)