# Web3Auth Documentation
Web3Auth (now MetaMask Embedded Wallets) is a pluggable embedded wallet infrastructure that simplifies Web3 wallet integration and user onboarding. It provides SDKs for multiple platforms including Web (React, Vue, JavaScript), Mobile (Android, iOS, React Native, Flutter), Gaming (Unity, Unreal), and Backend (Node.js). The platform enables developers to integrate Web3 authentication using familiar OAuth-based logins like Google, Facebook, and Discord, allowing users to access Web3 applications through existing authentication methods in under a minute.
The core functionality centers around non-custodial wallet management with Multi-Party Computation (MPC) for enhanced security. Users maintain full control of their wallets while enjoying seamless onboarding through social logins. Web3Auth supports connections to various blockchains including Ethereum, Solana, Bitcoin, and many EVM-compatible chains. Key features include smart accounts, external wallet aggregation, custom authentication providers, wallet pregeneration, session management, and server-side verification.
## Web SDK Integration (React)
The React SDK provides hooks-based integration for modern React applications with TypeScript support. It enables Web3 authentication with just a few lines of code, supporting various login providers and blockchain connections.
```tsx
// Install: npm install @web3auth/modal @web3auth/ethereum-provider
import { Web3Auth } from "@web3auth/modal";
import { CHAIN_NAMESPACES } from "@web3auth/base";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
// Configuration for Ethereum Mainnet
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1", // Ethereum Mainnet
rpcTarget: "https://rpc.ankr.com/eth",
displayName: "Ethereum Mainnet",
blockExplorerUrl: "https://etherscan.io",
ticker: "ETH",
tickerName: "Ethereum",
};
// Initialize Web3Auth
const privateKeyProvider = new EthereumPrivateKeyProvider({
config: { chainConfig },
});
const web3auth = new Web3Auth({
clientId: "YOUR_WEB3AUTH_CLIENT_ID", // Get from dashboard.web3auth.io
web3AuthNetwork: "sapphire_mainnet",
chainConfig,
privateKeyProvider,
});
// Initialize and connect
await web3auth.initModal();
const provider = await web3auth.connect();
// Get user info after login
const user = await web3auth.getUserInfo();
console.log("User:", user.email, user.name);
// Get Ethereum provider for transactions
const ethersProvider = new ethers.BrowserProvider(provider);
const signer = await ethersProvider.getSigner();
const address = await signer.getAddress();
console.log("Wallet Address:", address);
```
## Vue SDK Integration
The Vue SDK uses composables for flexible and reusable authentication logic, providing a native Vue development experience with reactive state management.
```vue
Welcome, {{ userInfo?.name }}
```
## JavaScript SDK Integration
The vanilla JavaScript SDK integrates with any frontend framework or plain HTML/JS applications, providing maximum flexibility for various project setups.
```javascript
// Install: npm install @web3auth/modal @web3auth/ethereum-provider
import { Web3Auth } from "@web3auth/modal";
import { CHAIN_NAMESPACES } from "@web3auth/base";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
class Web3AuthManager {
constructor(clientId) {
this.clientId = clientId;
this.web3auth = null;
this.provider = null;
}
async init() {
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x89", // Polygon Mainnet
rpcTarget: "https://rpc.ankr.com/polygon",
displayName: "Polygon Mainnet",
blockExplorerUrl: "https://polygonscan.com",
ticker: "MATIC",
tickerName: "Polygon",
};
const privateKeyProvider = new EthereumPrivateKeyProvider({
config: { chainConfig },
});
this.web3auth = new Web3Auth({
clientId: this.clientId,
web3AuthNetwork: "sapphire_mainnet",
chainConfig,
privateKeyProvider,
});
await this.web3auth.initModal();
if (this.web3auth.connected) {
this.provider = this.web3auth.provider;
}
}
async login() {
this.provider = await this.web3auth.connect();
return await this.web3auth.getUserInfo();
}
async logout() {
await this.web3auth.logout();
this.provider = null;
}
async getAccounts() {
if (!this.provider) throw new Error("Not connected");
const accounts = await this.provider.request({ method: "eth_accounts" });
return accounts;
}
async signMessage(message) {
if (!this.provider) throw new Error("Not connected");
const accounts = await this.getAccounts();
const signature = await this.provider.request({
method: "personal_sign",
params: [message, accounts[0]],
});
return signature;
}
}
// Usage
const web3AuthManager = new Web3AuthManager("YOUR_CLIENT_ID");
await web3AuthManager.init();
document.getElementById("loginBtn").onclick = async () => {
const user = await web3AuthManager.login();
console.log("Logged in:", user);
};
```
## Android SDK Integration
The Android SDK provides native Kotlin/Java integration for Android applications with full Web3Auth authentication features and blockchain connectivity.
```kotlin
// Add to build.gradle:
// implementation 'com.web3auth:web3auth-android-sdk:8.0.0'
import com.web3auth.core.Web3Auth
import com.web3auth.core.types.*
class MainActivity : AppCompatActivity() {
private lateinit var web3Auth: Web3Auth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
web3Auth = Web3Auth(
Web3AuthOptions(
context = this,
clientId = "YOUR_WEB3AUTH_CLIENT_ID",
network = Network.SAPPHIRE_MAINNET,
redirectUrl = Uri.parse("com.example.app://auth"),
whiteLabel = WhiteLabelData(
appName = "My App",
logoLight = "https://example.com/logo.png",
logoDark = "https://example.com/logo-dark.png",
defaultLanguage = Language.EN,
mode = ThemeModes.DARK
)
)
)
}
private fun login() {
val loginParams = LoginParams(
loginProvider = Provider.GOOGLE,
extraLoginOptions = ExtraLoginOptions(
login_hint = "user@example.com"
)
)
val loginCompletableFuture = web3Auth.login(loginParams)
loginCompletableFuture.whenComplete { response, error ->
if (error == null) {
val userInfo = response.userInfo
val privateKey = response.privKey
Log.d("Web3Auth", "User: ${userInfo?.email}")
Log.d("Web3Auth", "Private Key: $privateKey")
// Use private key with web3j for blockchain interactions
val credentials = Credentials.create(privateKey)
val walletAddress = credentials.address
Log.d("Web3Auth", "Wallet: $walletAddress")
} else {
Log.e("Web3Auth", "Login failed", error)
}
}
}
private fun logout() {
val logoutCompletableFuture = web3Auth.logout()
logoutCompletableFuture.whenComplete { _, error ->
if (error == null) {
Log.d("Web3Auth", "Logged out successfully")
}
}
}
}
```
## iOS SDK Integration (Swift)
The iOS SDK provides seamless Swift integration with full Web3Auth features for iOS and macOS applications.
```swift
// Add via SPM: https://github.com/Web3Auth/web3auth-swift-sdk
import Web3Auth
import UIKit
class ViewController: UIViewController {
var web3Auth: Web3Auth?
override func viewDidLoad() {
super.viewDidLoad()
Task {
await initializeWeb3Auth()
}
}
func initializeWeb3Auth() async {
do {
web3Auth = try await Web3Auth(
W3AInitParams(
clientId: "YOUR_WEB3AUTH_CLIENT_ID",
network: .sapphire_mainnet,
redirectUrl: "com.example.app://auth",
whiteLabel: W3AWhiteLabelData(
appName: "My iOS App",
logoLight: "https://example.com/logo.png",
logoDark: "https://example.com/logo-dark.png",
defaultLanguage: .en,
mode: .dark
)
)
)
} catch {
print("Web3Auth initialization failed: \(error)")
}
}
@IBAction func loginWithGoogle(_ sender: UIButton) {
Task {
do {
let result = try await web3Auth?.login(
W3ALoginParams(
loginProvider: .GOOGLE,
extraLoginOptions: ExtraLoginOptions(
login_hint: "user@example.com"
)
)
)
if let userInfo = result?.userInfo {
print("User: \(userInfo.email ?? "No email")")
print("Name: \(userInfo.name ?? "No name")")
}
if let privateKey = result?.privKey {
print("Private Key: \(privateKey)")
// Use private key with web3.swift for transactions
}
} catch {
print("Login failed: \(error)")
}
}
}
@IBAction func logout(_ sender: UIButton) {
Task {
do {
try await web3Auth?.logout()
print("Logged out successfully")
} catch {
print("Logout failed: \(error)")
}
}
}
}
```
## Node.js Backend SDK
The Node.js SDK enables server-side authentication and key management for backend applications, AI agents, and programmatic wallet operations.
```javascript
// Install: npm install @web3auth/node-sdk
import { Web3Auth } from "@web3auth/node-sdk";
import jwt from "jsonwebtoken";
// Initialize Web3Auth Node SDK
const web3auth = new Web3Auth({
clientId: "YOUR_WEB3AUTH_CLIENT_ID",
web3AuthNetwork: "sapphire_mainnet",
});
// Initialize the SDK
await web3auth.init();
// Generate a JWT for custom authentication
function generateJWT(userId, email) {
const privateKey = fs.readFileSync("private_key.pem");
const token = jwt.sign(
{
sub: userId,
email: email,
aud: "urn:api-web3auth-io",
iss: "https://your-domain.com",
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 60 * 60, // 1 hour
},
privateKey,
{ algorithm: "RS256", keyid: "your-key-id" }
);
return token;
}
// Get user's private key using JWT authentication
async function getUserPrivateKey(userId, email) {
const idToken = generateJWT(userId, email);
const provider = await web3auth.connect({
verifier: "your-custom-verifier",
verifierId: userId,
idToken: idToken,
});
// Get the private key
const privateKey = await provider.request({
method: "eth_private_key",
});
return privateKey;
}
// Express.js endpoint example
app.post("/api/wallet", async (req, res) => {
try {
const { userId, email } = req.body;
const privateKey = await getUserPrivateKey(userId, email);
// Create wallet instance for transactions
const wallet = new ethers.Wallet(privateKey);
const address = wallet.address;
res.json({ address, success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Server-side transaction signing
async function signTransaction(userId, email, txData) {
const privateKey = await getUserPrivateKey(userId, email);
const wallet = new ethers.Wallet(privateKey, provider);
const tx = await wallet.sendTransaction({
to: txData.to,
value: ethers.parseEther(txData.amount),
data: txData.data || "0x",
});
return tx.hash;
}
```
## Custom Authentication with JWT Verifier
Web3Auth supports custom authentication using JWT tokens from your own identity provider, enabling integration with existing user management systems.
```javascript
// Dashboard Setup: Create a Custom JWT Verifier at dashboard.web3auth.io
import { Web3Auth } from "@web3auth/modal";
import { WALLET_ADAPTERS, CHAIN_NAMESPACES } from "@web3auth/base";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";
// Initialize with custom verifier
const web3auth = new Web3Auth({
clientId: "YOUR_WEB3AUTH_CLIENT_ID",
web3AuthNetwork: "sapphire_mainnet",
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth",
},
});
// Configure OpenLogin adapter for JWT
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
loginConfig: {
jwt: {
verifier: "your-custom-verifier-name",
typeOfLogin: "jwt",
clientId: "YOUR_WEB3AUTH_CLIENT_ID",
},
},
},
});
web3auth.configureAdapter(openloginAdapter);
await web3auth.initModal();
// Login with your JWT token
async function loginWithJWT(idToken) {
const provider = await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
loginProvider: "jwt",
extraLoginOptions: {
id_token: idToken,
verifierIdField: "sub", // Field in JWT containing user ID
domain: "https://your-auth-domain.com",
},
});
const userInfo = await web3auth.getUserInfo();
console.log("Authenticated user:", userInfo);
return provider;
}
// Example: Get JWT from your backend and authenticate
async function authenticate() {
// Fetch JWT from your authentication server
const response = await fetch("/api/auth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: "user@example.com", password: "****" }),
});
const { idToken } = await response.json();
const provider = await loginWithJWT(idToken);
// Now use provider for blockchain interactions
const accounts = await provider.request({ method: "eth_accounts" });
console.log("Wallet address:", accounts[0]);
}
```
## Multi-Chain Connection
Web3Auth supports connecting to multiple blockchains including EVM chains, Solana, and other networks through unified provider interfaces.
```javascript
import { Web3Auth } from "@web3auth/modal";
import { CHAIN_NAMESPACES } from "@web3auth/base";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { SolanaPrivateKeyProvider } from "@web3auth/solana-provider";
// Ethereum configuration
const ethChainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth",
displayName: "Ethereum Mainnet",
ticker: "ETH",
};
// Solana configuration
const solanaChainConfig = {
chainNamespace: CHAIN_NAMESPACES.SOLANA,
chainId: "0x1", // Mainnet
rpcTarget: "https://api.mainnet-beta.solana.com",
displayName: "Solana Mainnet",
ticker: "SOL",
};
// Polygon configuration
const polygonChainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x89",
rpcTarget: "https://rpc.ankr.com/polygon",
displayName: "Polygon Mainnet",
ticker: "MATIC",
};
// Initialize with Ethereum
const ethProvider = new EthereumPrivateKeyProvider({
config: { chainConfig: ethChainConfig },
});
const web3auth = new Web3Auth({
clientId: "YOUR_WEB3AUTH_CLIENT_ID",
web3AuthNetwork: "sapphire_mainnet",
chainConfig: ethChainConfig,
privateKeyProvider: ethProvider,
});
await web3auth.initModal();
const provider = await web3auth.connect();
// Switch to Polygon
await web3auth.addChain(polygonChainConfig);
await web3auth.switchChain({ chainId: "0x89" });
// Get balance on current chain
async function getBalance(address) {
const balance = await provider.request({
method: "eth_getBalance",
params: [address, "latest"],
});
return parseInt(balance, 16) / 1e18;
}
// Send transaction
async function sendTransaction(to, amount) {
const accounts = await provider.request({ method: "eth_accounts" });
const txHash = await provider.request({
method: "eth_sendTransaction",
params: [{
from: accounts[0],
to: to,
value: "0x" + (amount * 1e18).toString(16),
gas: "0x5208", // 21000 gas
}],
});
console.log("Transaction hash:", txHash);
return txHash;
}
```
## Summary
Web3Auth provides a comprehensive solution for Web3 authentication and wallet management across all major platforms. The primary use cases include onboarding Web2 users to Web3 applications through familiar social logins (Google, Facebook, Discord, Twitter), integrating non-custodial wallets into existing applications without requiring users to manage seed phrases, and building cross-platform dApps that work seamlessly on web, mobile, and gaming platforms. Enterprise applications benefit from custom authentication integration using JWT verifiers, enabling organizations to maintain their existing identity infrastructure while adding Web3 capabilities.
Integration patterns typically follow a three-step approach: initialize the Web3Auth SDK with your client ID and chain configuration, call the connect method to trigger the authentication flow, and use the returned provider for blockchain interactions. The SDKs are designed to work with popular libraries like ethers.js, web3.js, and platform-specific blockchain SDKs. For production deployments, developers should configure whitelabeling options to match their brand, set up proper redirect URLs in the Web3Auth dashboard, and implement appropriate error handling for network issues and user cancellations. The MPC-based key management ensures that user keys are never exposed to any single party, providing enterprise-grade security while maintaining a seamless user experience.