Skip to main content

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.

JavaScript SDK Quickstart

Prerequisites

Set up using a template

  1. Download the MetaMask Connect JavaScript template:

    npx degit MetaMask/metamask-sdk-examples/quickstarts/javascript metamask-javascript
  2. Navigate into the repository:

    cd metamask-javascript
    Degit vs. Git clone

    degit is a tool that enables cloning only the directory structure from a GitHub repository, without retrieving the entire repository.

    Alternatively, use git clone to download the entire repository. Clone the MetaMask Connect examples repository and navigate into the quickstarts/javascript directory:

    git clone https://github.com/MetaMask/metamask-sdk-examples
    cd metamask-sdk-examples/quickstarts/javascript
  3. Install dependencies:

    pnpm install
  4. Create a .env.local file:

    touch .env.local
  5. In .env.local, add a VITE_INFURA_API_KEY environment variable, replacing <YOUR-API-KEY> with your Infura API key:

    .env.local
    VITE_INFURA_API_KEY=<YOUR-API-KEY>
  6. 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 install @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's name, url, and iconUrl during connection.
  • api.supportedNetworks - A map of hex chain IDs to RPC URLs for all networks supported by the app. Use the getInfuraRpcUrls helper to generate URLs for all Infura-supported chains, or specify your own.
createEVMClient is async

createEVMClient 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

MethodDescription
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 RPCUse 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' }],
})

Live example