Skip to main content

Embedded Wallets SDK for React Native

Overview

MetaMask Embedded Wallets SDK (formerly Web3Auth Plug and Play/ W3A PnP) provides a seamless authentication experience for React Native applications with social logins, external wallets, and more. Using our React Native SDK, you can easily connect users to their preferred wallets and manage authentication state across both iOS and Android platforms.

Requirements

  • React Native Release 0.71 and above (for Bare React Native Workflow)
  • Expo SDK 48 and above (for Expo Managed Workflow)
  • iOS Platform Target Version 14 and above
  • Android Target SDK Version 31 and above
  • Basic knowledge of JavaScript/TypeScript and React Native

Selecting your Workflow

In React Native, you have the choice to use one of the following workflows:

Bare React Native Workflow

Your Bare React Native app is entirely built on your machine. In this workflow, the developer has complete control, along with the complexity that comes with that.

Expo Managed Workflow

Your Expo app is built on your Expo's cloud, so you don't have control over the native modules used in the app. Developers build managed workflow apps using expo-cli on their computers and a development client on their mobile devices.

note

The Web3Auth React Native PnP SDK is not compatible with "Expo Go" app. It is compatible only with Custom Dev Client and EAS builds.

Please run npx expo prebuild to generate native code based on the version of expo a project has installed, before moving forward.

Installation

1. Install Web3Auth React Native SDK

npm install --save @web3auth/react-native-sdk

2. Install Helper Modules

Install required helper modules for WebBrowser and Storage:

  • A WebBrowser implementation is needed to allow our JS-based SDK to interact with the native APIs.
  • A Storage implementation is needed to store the user's session, without storing the private keys of the user in the device.
npm install --save @toruslabs/react-native-web-browser react-native-encrypted-storage

Setup

info

Prerequisites Before you start, make sure you have registered on the Web3Auth Dashboard and have set up your project. You can look into the Dashboard Setup guide to learn more.

Android

  • Make sure that the minimum SDK compile version in build.gradle is 31 or more.

    build.gradle
    buildToolsVersion = "31.0.0"
    minSdkVersion = 21
    compileSdkVersion = 31
    targetSdkVersion = 31
  • Add the intent filter with scheme defined in your AndroidManifest.xml

    AndroidManifest.xml
    <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    # replace with your own scheme
    <data android:scheme="web3authrnexample" />
    </intent-filter>
  • SDK version 31 requires you to explicitly define android:exported="true" in AndroidManifest.xml, and check whether it is correctly present or not.

    AndroidManifest.xml
    <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
    android:launchMode="singleTask"
    android:windowSoftInputMode="adjustResize"
    android:exported="true">
  • Your redirectUrl is your defined scheme following some identifier or your choice. For example, if your scheme is web3authrnexample, you can define your redirectUrl as web3authrnexample://auth. Make sure you register this redirectUrl in the Web3Auth Developer Dashboard.

    const scheme = 'web3authrnexample' // Or your desired app redirection scheme
    const resolvedRedirectUrl = `${scheme}://auth`

iOS

  • Make sure that the minimum SDK compile version in Podfile is 14 or more.

    Podfile
    platform: ios, '14'
  • Install the Cocoa Pods within your project directory.

    cd ios
    pod install
  • In iOS, you don't need to add redirectUrl as an iOS Custom URL Scheme, however, you may add it to your Info.plist, but it is not required. Make sure your redirectUrl is registered in the Web3Auth Developer Dashboard.

Expo Managed Workflow

  • Update the scheme in your app.json file.

    app.json
    {
    "expo": {
    "scheme": "web3authexpoexample" // replace with your own scheme
    }
    }
  • For constructing your redirectUrl, you'll need to use the expo-linking, which will help you generate a redirectUrl for your app. Make sure you register that URL in the Web3Auth Developer Dashboard.

    import Constants, { AppOwnership } from 'expo-constants'
    import * as Linking from 'expo-linking'

    const resolvedRedirectUrl =
    Constants.appOwnership == AppOwnership.Expo || Constants.appOwnership == AppOwnership.Guest
    ? Linking.createURL('web3auth', {})
    : Linking.createURL('web3auth', { scheme: 'web3authexpoexample' }) // replace with your own scheme

Initialize Web3Auth

1. Create a Web3Auth Instance

Create a configuration file for Web3Auth. This file will contain your Web3Auth Client ID and Network details from the Web3Auth Dashboard.

App.tsx
import Web3Auth, { WEB3AUTH_NETWORK, LOGIN_PROVIDER } from '@web3auth/react-native-sdk'
import * as WebBrowser from '@toruslabs/react-native-web-browser'
import EncryptedStorage from 'react-native-encrypted-storage'

const scheme = 'web3authrnexample' // Or your desired app redirection scheme
const resolvedRedirectUrl = `${scheme}://auth`

const web3auth = new Web3Auth(WebBrowser, EncryptedStorage, {
clientId: 'YOUR_CLIENT_ID', // Get your Client ID from Web3Auth Dashboard
network: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // or WEB3AUTH_NETWORK.SAPPHIRE_DEVNET
redirectUrl: resolvedRedirectUrl,
})

2. Initialize the Web3Auth Instance

Initialize the Web3Auth instance before using any authentication methods:

App.tsx
import { useEffect } from 'react'

useEffect(() => {
const init = async () => {
try {
await web3auth.init()
console.log('Web3Auth initialized successfully')
} catch (error) {
console.error('Error initializing Web3Auth:', error)
}
}
init()
}, [])

Advanced Configuration

The Web3Auth React Native SDK offers a rich set of advanced configuration options:

tip

Head over to the advanced configuration sections to learn more about each configuration option.

import Web3Auth, { WEB3AUTH_NETWORK } from '@web3auth/react-native-sdk'

const web3auth = new Web3Auth(WebBrowser, SecureStore, {
clientId: 'YOUR_CLIENT_ID',
network: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // or WEB3AUTH_NETWORK.SAPPHIRE_DEVNET
redirectUrl: resolvedRedirectUrl,
})

Blockchain Integration

Web3Auth is blockchain agnostic, enabling integration with any blockchain network. Out of the box, Web3Auth offers robust support for both Solana and Ethereum.

Ethereum Integration

For Ethereum integration, you can get the provider and use it with ethers or viem:

// Import the required shims
import '@ethersproject/shims'
// Import the ethers library
import { ethers } from 'ethers'
// Import the Web3Auth Ethereum Provider
import { EthereumPrivateKeyProvider } from '@web3auth/ethereum-provider'

// Define the chain config for the EVM network
chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: '0x1',
rpcTarget: 'https://rpc.ethereum.org',
displayName: 'Ethereum Mainnet',
blockExplorer: 'https://etherscan.io',
ticker: 'ETH',
tickerName: 'Ethereum',
}

// Create an instance of the Web3Auth Ethereum Provider
const ethereumPrivateKeyProvider = new EthereumPrivateKeyProvider({
config: {
chainConfig,
},
})

// Setup the provider with the Web3Auth Private Key
await ethereumPrivateKeyProvider.setupProvider(web3auth.privKey)

// Create an instance of the ethers BrowserProvider using the Web3Auth Ethereum Provider
const ethersProvider = new ethers.BrowserProvider(ethereumPrivateKeyProvider)

// Get the signer for ethers
const signer = await ethersProvider.getSigner()

// Get the address of the user
const address = signer.getAddress()

// Get the balance of the user
const balance = ethers.formatEther(
await ethersProvider.getBalance(address) // Balance is in wei
)

Solana Integration

For Solana integration, you can get the private key and use it with Solana libraries:

const getSolanaAccount = async () => {
try {
const privateKey = await web3auth.getPrivKey()
// Use private key with Solana libraries
console.log('Solana private key:', privateKey)
} catch (error) {
console.error('Error getting private key:', error)
}
}

Troubleshooting

Bundler Polyfill Issues

While using Web3Auth in React Native, you may run into issues building. This issue occurs because some core packages like eccrypto have certain dependencies which are not present within the Metro build environment.

To solve this, please have a look at our troubleshooting page for React Native Metro Bundler Issues