Login | MetaMask Developer

Implementing secure wallet login for your dApps using MetaMask

Introduction

MetaMask provides developers with a secure, non-custodial way to authenticate users directly from their browser wallet. Instead of handling credentials, you can leverage MetaMask login flows to sign messages, validate ownership of addresses, and integrate wallet-based authentication in your decentralized applications.

How MetaMask Login Works

  1. User installs and unlocks the MetaMask extension in Chrome or another browser.
  2. Your dApp requests account access using ethereum.request({ method: 'eth_requestAccounts' }).
  3. The user approves the connection, granting your dApp permission to interact with their wallet.
  4. You can request a signed message for authentication and verify it server-side.

Code Example: Requesting Accounts

// Request account access
if (typeof window.ethereum !== 'undefined') {
  const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
  console.log("Connected account:", accounts[0]);
} else {
  console.log("MetaMask is not installed");
}
        

Implementing Login with Message Signing

Developers can implement secure login by signing a challenge string (nonce) with MetaMask. The signed message proves that the user controls the private key associated with their wallet.

// Signing a message
const message = "Login request: " + new Date().toISOString();
const from = accounts[0];

const signature = await ethereum.request({
  method: 'personal_sign',
  params: [message, from],
});

console.log("Signature:", signature);
        

Best Practices for Developers

Resources

Explore more about integrating MetaMask in your projects:

MetaMask Developer Docs