Connect to MetaMask using JavaScript
Get started with MetaMask Connect EVM in your JavaScript dapp. Download the quickstart template or manually set up MetaMask Connect EVM in an existing dapp.
Prerequisites
- Node.js version 19 or later installed.
- A package manager installed, such as npm, Yarn, pnpm, or bun.
- MetaMask installed in your browser or on mobile.
- An Infura API key from the MetaMask Developer dashboard.
Set up using a template
-
Download the MetaMask Connect JavaScript template:
npx degit MetaMask/metamask-sdk-examples/quickstarts/javascript metamask-javascript -
Navigate into the repository:
cd metamask-javascriptDegit vs. Git clone
degitis a tool that enables cloning only the directory structure from a GitHub repository, without retrieving the entire repository.Alternatively, use
git cloneto download the entire repository. Clone the MetaMask Connect examples repository and navigate into thequickstarts/javascriptdirectory:git clone https://github.com/MetaMask/metamask-sdk-examples
cd metamask-sdk-examples/quickstarts/javascript -
Install dependencies:
pnpm install -
Create a
.env.localfile:touch .env.local -
In
.env.local, add aVITE_INFURA_API_KEYenvironment variable, replacing<YOUR-API-KEY>with your Infura API key:.env.localVITE_INFURA_API_KEY=<YOUR-API-KEY> -
Run the project:
pnpm dev
You've successfully set up MetaMask Connect EVM.
Set up manually
1. Install MetaMask Connect EVM
Install MetaMask Connect EVM in an existing JavaScript project:
- npm
- Yarn
- pnpm
- Bun
npm install @metamask/connect-evm
yarn add @metamask/connect-evm
pnpm add @metamask/connect-evm
bun add @metamask/connect-evm
2. Initialize MetaMask Connect EVM
The following is an example of using MetaMask Connect EVM for an EVM dapp in a JavaScript project:
import { createEVMClient, getInfuraRpcUrls } from '@metamask/connect-evm'
const evmClient = await createEVMClient({
dapp: {
name: 'Metamask Connect EVM Example',
url: window.location.href,
iconUrl: 'https://mydapp.com/icon.png', // Optional
},
api: {
supportedNetworks: {
...getInfuraRpcUrls('YOUR_INFURA_API_KEY'),
'0x1': 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
'0xaa36a7': 'https://sepolia.infura.io/v3/YOUR_INFURA_API_KEY',
},
},
})
These examples configure MetaMask Connect EVM with the following options:
dapp- Ensures trust by showing your dapp'sname,url, andiconUrlduring connection.api.supportedNetworks- A map of hex chain IDs to RPC URLs for all networks supported by the app. Use thegetInfuraRpcUrlshelper to generate URLs for all Infura-supported chains, or specify your own.
createEVMClient is asynccreateEVMClient returns a promise. Always await it before using the client.
The client is a singleton -- calling createEVMClient again returns the same instance.
3. Connect and use provider
Connect to MetaMask and get the provider for RPC requests:
const provider = evmClient.getProvider()
try {
const { accounts, chainId } = await evmClient.connect({
chainIds: ['0x1', '0xaa36a7'],
})
console.log('Connected account:', accounts[0])
console.log('Active chain:', chainId)
} catch (error) {
if (error.code === 4001) {
console.log('User rejected the connection request')
} else if (error.code === -32002) {
console.log('Connection request already pending')
} else {
console.error('Connection failed:', error)
}
}
const balance = await provider.request({
method: 'eth_getBalance',
params: [accounts[0], 'latest'],
})
console.log('Balance:', balance)
evmClient.connect() handles cross-platform connection (desktop and mobile), including deeplinking.
Pass chainIds to request permission for specific chains (hex strings). Ethereum Mainnet (0x1)
is always included regardless of what you pass.
Use provider.request() for arbitrary JSON-RPC requests like eth_chainId or eth_getBalance, or for batching requests via metamask_batch.
Common MetaMask Connect EVM methods at a glance
| Method | Description |
|---|---|
connect() | Triggers wallet connection flow |
connectAndSign({ message: "..." }) | Connects and prompts the user to sign a message |
getProvider() | Returns the provider object for RPC requests |
provider.request({ method, params }) | Calls any Ethereum JSON‑RPC method |
| Batched RPC | Use metamask_batch to group multiple JSON-RPC requests |
Usage example
// 1. Connect and get accounts
const { accounts, chainId } = await evmClient.connect()
// 2. Connect and sign in one step
const signature = await evmClient.connectAndSign({
message: 'Sign in to the dapp',
})
// 3. Get provider for RPC requests
const provider = evmClient.getProvider()
// 4. Make an RPC request
const result = await provider.request({
method: 'eth_accounts',
params: [],
})
// 5. Batch multiple RPC requests
const batchResults = await provider.request({
method: 'metamask_batch',
params: [{ method: 'eth_accounts' }, { method: 'eth_chainId' }],
})
