React Native

React Native

#Overview

The Magic SDK for React Native is your entry-point to secure, passwordless authentication for your mobile app. This guide will cover some important topics for getting started with React Native APIs and to make the most of Magic's features.

#Getting Started

The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic publishable API key.

#Installation

The Magic SDK for React Native supports both Bare and Expo. Follow the installation steps relevant to your setup.

Bare NPM
Bare Yarn
Expo NPM
Expo Yarn
01npm install --save @magic-sdk/react-native-bare
02npm install --save react-native-device-info # Required Peer Dependency
03npm install --save @react-native-community/async-storage # Required Peer Dependency
04npm install --save react-native-safe-area-context # Required Peer Dependency
05
06# For iOS
07cd ios
08⁠pod install
09
10# Start your app
11⁠cd /path/to/project/root
12yarn start
13

#Constructor

#Magic()

Configure and construct your Magic SDK instance.

Parameter

Type

Definition

apiKey

String

Your publishable API Key retrieved from the Magic Dashboard.

options.locale?

String

Customize the language of Magic's modal, email and confirmation screen. See Localization for more.

options.testMode?

Boolean

Enable testMode to assert the desired behavior through the email address you provide to loginWithMagicLink without having to go through the auth flow.

options.network?

String | Object

(String): A representation of the connected Ethereum network (mainnet or goerli).

⁠(Object): A custom Ethereum Node configuration with the following shape:

rpcUrl (String): A URL pointing to your custom Ethereum Node.⁠⁠

chainId? (Number): Some Node infrastructures require you to pass an explicit chain ID. If you are aware that your Node requires this configuration, pass it here as an integer.

options.endpoint?

String

A URL pointing to the Magic <iframe> application.

options.deferPreload?

Boolean

An optional flag to delay the loading of the Magic Iframe's static assets until an SDK function is explicitly invoked. ⁠⁠⁠Set this to true if latency bottlenecks are a concern.

options.useStorageCache?

Boolean

An optional flag to allow the usage of the local storage as cache. Currently it is only used for faster calls to isLoggedIn. When set to true, the magic.user.onUserLoggedOut event listener needs to be used.

#Initialization

Initialize Magic instance.

Bare
Expo
01import { Magic } from '@magic-sdk/react-native-bare'
02
03const magic = new Magic('PUBLISHABLE_API_KEY')

#Relayer

To facilitate events between the Magic <iframe> context and your React Native application, the <Relayer> React component must be exposed on your Magic instance.

#Arguments

  • backgroundColor? (String): Used to render a custom background color. By default, the background will be white. If you have changed the background color as part of your custom branding setup, make sure to pass that color to magic.Relayer.

#Example

JSX
01function App() {
02  return (
03    <SafeAreaProvider>
04      {/* Remember to render the `Relayer` component into your app! */}
05      <m.Relayer />
06    </SafeAreaProvider>
07  );
08}

#Auth Module

The Auth Module and it's members are accessible on the Magic SDK instance by the auth property.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08magic.auth;
09magic.auth.loginWithEmailOTP;
10magic.auth.loginWithSMS;
11magic.auth.loginWithCredential;
12magic.auth.updateEmailWithUI;

#loginWithEmailOTP

Authenticate a user passwordlessly using an email one-time code sent to the specified user's email address.

note

Only available with Dedicated Wallet.

#Arguments

  • email (String): The user email to log in with
  • showUI? (Boolean): If true, show an out-of-the-box UI to accept the OTP from user
  • deviceCheckUI? (Boolean): The default value is true. It shows Magic branded UI securing sign-ins from new devices. If set to false, the UI will remain hidden. However, this the false value only takes effect when you have also set the showUI: false. ⁠Available since [email protected].

#Returns

  • PromiEvent<string | null>: The promise resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// log in a user by their email
09try {
10  await magic.auth.loginWithEmailOTP({ email: '[email protected]' });
11} catch {
12  // Handle errors if required!
13}
14
15// log in a user by their email, without showing an out-of-the box UI.
16try {
17  await magic.auth.loginWithEmailOTP({ email: '[email protected]', showUI: false });
18} catch {
19  // Handle errors if required!
20}

#Event Handling

Relevant Events

A white-label OTP login flow is available when passing showUI: false to this login method. Here's a short example to illustrate listening for and emitting events during the login flow:

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  // Initiate login flow
10  const handle = magic.auth.loginWithEmailOTP({ email: "[email protected]", showUI: false, deviceCheckUI: false });
11
12  handle
13  .on('email-otp-sent', () => {
14    // The email has been sent to the user
15
16    // Prompt the user for the OTP
17    const otp = window.prompt('Enter Email OTP');
18
19    // Send the OTP for verification
20    handle.emit('verify-email-otp', otp);
21  })
22  .on('invalid-email-otp', () => {
23    // User entered invalid OTP
24
25    /* 
26      Have the user retry entering the OTP.
27      Then emit the "verify-email-otp" event with the OTP.
28    */
29
30    /*
31      You may limit the amount of retries and
32      emit a "cancel" event to cancel the login request.
33    */
34
35    // cancel login request
36    handle.emit('cancel');
37  })
38  .on('done', (result) => {
39    // is called when the Promise resolves
40
41    // convey login success to user
42    alert('Login complete!');
43		
44    // DID Token returned in result
45    const didToken = result;
46  })
47  .on('error', (reason) => {
48    // is called if the Promise rejects
49    console.error(reason);
50  })
51  .on('settled', () => {
52    // is called when the Promise either resolves or rejects
53  }) 
54
55  /**
56   * Device Verification Events
57   */
58  .on('device-needs-approval', () => {
59    // is called when device is not recognized and requires approval
60  })
61  .on('device-verification-email-sent', () => {
62    // is called when the device verification email is sent 
63  })
64  .on('device-approved', () => {
65    // is called when the device has been approved
66  })
67  .on('device-verification-link-expired', () => {
68    // is called when the device verification link is expired
69    // Retry device verification
70    handle.emit('device-retry');
71  });
72
73  /*
74     In typescript, you may use DeviceVerificationEventOnReceived types for strong typing
75  */ 
76  /* 
77     You may use 'cancel' from white-label otp event 
78     to terminate the unresolved request
79  */
80} catch (err) {
81  // handle errors
82}

#Events

Email OTP

Event NameDefinition
email-otp-sentDispatched when the OTP email has been successfully sent from the Magic server.
verify-email-otpEmit along with the OTP to verify the code from user.
invalid-email-otpDispatched when the OTP sent fails verification.

cancel

Emit to cancel the login request.

Device Verification

Event NameDefinition
device-needs-approvalDispatched when the device is unrecognized and requires user approval
device-verification-email-sentDispatched when the device verification email is sent
device-approvedDispatched when the user has approved the unrecongized device

device-verification-link-expired

Dispatched when the email verification email has expired

device-retry

Emit to restart the device registration flow

#Error Handling

To achieve a fully white-labeled experience, you will need to implement some custom error handling according to your UI needs. Here's a short example to illustrate how errors can be caught and identified by their code:

Javascript
01// Bare React Native
02import { Magic, RPCError, RPCErrorCode } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic, RPCError, RPCErrorCode } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await magic.auth.loginWithEmailOTP({ email: '[email protected]' });
10} catch (err) {
11  if (err instanceof RPCError) {
12    switch (err.code) {
13      case RPCErrorCode.MagicLinkExpired
14      case RPCErrorCode.UserAlreadyLoggedIn:
15        // Handle errors accordingly :)
16        break;
17    }
18  }
19}

#loginWithSMS

Authenticate a user passwordlessly using a one-time code sent to the specified phone number.

List of Currently Blocked Country Codes

note

Only available with Dedicated Wallet.

#Arguments

  • phoneNumber (String): E.164 formatted phone number

#Returns

  • PromiEvent<string | null>: The promise resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// log in a user by their phone number
09try {
10  await magic.auth.loginWithSMS({ '+14151231234' });
11} catch {
12  // Handle errors if required!
13}

#Error Handling

Relevant Error Codes

To achieve a fully white-labeled experience, you will need to implement some custom error handling according to your UI needs. Here's a short example to illustrate how errors can be caught and identified by their code:

Javascript
01// Bare React Native
02import { Magic, RPCError, RPCErrorCode } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic, RPCError, RPCErrorCode } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await magic.auth.loginWithSMS({ phoneNumber: "+14151231234" });
10} catch (err) {
11  if (err instanceof RPCError) {
12    switch (err.code) {
13      case RPCErrorCode.AccessDeniedToUser:
14      case RPCErrorCode.MagicLinkRateLimited:
15      case RPCErrorCode.UserAlreadyLoggedIn:
16        // Handle errors accordingly :)
17        break;
18    }
19  }
20}

#loginWithCredential

Authenticate a user via a "Magic Credential," a special, one-time-use DID Token created by the user to hydrate their authentication between page reloads. For example: when executing the loginWithMagicLink flow with a redirectURI specified, you can invoke this method to complete the authentication "callback," similar in principal to OAuth 2.0 flows.

If given no arguments, this method will parse the credential token automatically from window.location.search.

note

Only available with Dedicated Wallet.

#Arguments

  • credentialOrQueryString (String): A credential token or a valid query string (prefixed with ? or #). By default, this method will look for the a credential token on the magic_credential key of window.location.search.

#Returns

  • PromiEvent<string | null>: The promise resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

#Example

From your login page:

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await magic.auth.loginWithMagicLink({
10    email: '[email protected]',
11    redirectURI: 'https://yourdomain.com/your/magic/link/callback',
12  });
13
14  // When the user clicks their magic link, they will be logged-in here
15  // and in the "callback" context.
16} catch {
17  // Handle errors if required!
18}

From your authentication callback page:

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await magic.auth.loginWithCredential();
10} catch {
11  // Handle errors if required!
12}
13
14// You can also provide the credential yourself
15try {
16  await magic.auth.loginWithCredential('iamacredentialtoken');
17} catch {
18  // Handle errors if required!
19}
20
21// You can also provide the credential as a query string
22try {
23  await magic.auth.loginWithCredential(window.location.search);
24} catch {
25  // Handle errors if required!
26}

#updateEmailWithUI

Initiates the update email flow that allows a user to change their email address.

note

Only available with Dedicated Wallet.

#Arguments

  • email (String): The new email to update to
  • showUI? (Boolean): If true, shows an out-of-the-box pending UI which includes instructions on which step of the confirmation process the user is on. Dismisses automatically when the process is complete.

#Returns

  • PromiEvent<boolean>: The promise resolves with a true boolean value if update email is successful and rejects with a specific error code if the request fails

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// Initiates the flow to update a user's current email to a new one.
09try {
10  ...
11  /* Assuming user is logged in */
12  await magic.auth.updateEmailWithUI({ email: '[email protected]' });
13} catch {
14  // Handle errors if required!
15}
16
17/**
18 * Initiates the flow to update a user's current email to a new one,
19 * without showing an out-of-the box UI.
20 */
21try {
22  /* Assuming user is logged in */
23  await magic.auth.updateEmailWithUI({ email: '[email protected]', showUI: false });
24} catch {
25  // Handle errors if required!
26}

#Error Handling

Relevant Error Codes

To achieve a fully white-labeled experience, you will need to implement some custom error handling according to your UI needs. Here's a short example to illustrate how errors can be caught and identified by their code:

Javascript
01// Bare React Native
02import { Magic, RPCError, RPCErrorCode } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic, RPCError, RPCErrorCode } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await magic.auth.updateEmailWithUI({ email: '[email protected]', showUI: false });
10} catch (err) {
11  if (err instanceof RPCError) {
12    switch (err.code) {
13      case RPCErrorCode.UpdateEmailFailed:
14        // Handle errors accordingly :)
15        break;
16    }
17  }
18}

#Events

Event NameDefinition
new-email-confirmedDispatched when the magic link has been clicked from the user’s new email address.
email-sentDispatched when the magic link email has been successfully sent from the Magic Link server to the user’s new email address.
email-not-deliverableDispatched if the magic link email is unable to be delivered to the user’s new email address.
old-email-confirmed Dispatched when the magic link has been clicked from the user’s previous email address.
retryDispatched when the user restarts the flow. This can only happen if showUI: true.

#Wallet Module

The Wallet Module and it's members are accessible on the Magic SDK instance by the wallet property. ⁠ ⁠Note: The Wallet Module is currently only compatiable with Ethereum, Polygon, Flow (no NFTs), and Optimism.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08magic.wallet;
09magic.wallet.connectWithUI;
10magic.wallet.showUI;
11magic.wallet.showAddress;
12magic.wallet.showBalances;
13magic.wallet.showNFTs;
14magic.wallet.showSendTokensUI;
15magic.wallet.showOnRamp; // enterprise only
16magic.wallet.getProvider;

#connectWithUI

Renders a simple login form UI to collect the user's email address and authenticate them passwordlessly using a one-time passcode (OTP) sent to their email address they input.

#Arguments

  • None

#Returns

  • A promiEvent which returns an String[] when resolved: An array of user accounts that are connected, with the first element being the current public address of the user. You can read more on PromiEvents here.

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const accounts = await magic.wallet.connectWithUI();
07
08/* Optionally, chain to the id token creation event if needed and configured */
09magic.wallet.connectWithUI().on('id-token-created', (params) => {
10 const { idToken } = params
11 console.log(idToken)
12 // send to your resource server for validation
13 // ...
14});

#Events

Event Name

Definition

id-token-created

Returns an object containing a short lived, time bound ID token that can be used to verify the ownership of a user's wallet address on login.

Read more about this token and how to use it.

#showUI

Displays the fully navigable wallet to the user that adheres to the toggled configurations on your developer dashboard’s Widget UI tab. ⁠ ⁠This is only supported for users who login with email or Google and not third party wallets such as metamask. User must be signed in for this method to return or else it will throw an error.

#Arguments

  • None

#Returns

  • Promise which resolves when the user closes the window

⁠Optionally, add a .on() handler to catch the disconnect event emitted when the user logs out from the wallet widget.

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08await magic.wallet.showUI()

#showAddress

Displays an iframe with the current user’s wallet address in a QR Code.

#Arguments

  • None

#Returns

  • Promise which resolves when the user closes the window

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08await magic.wallet.showAddress()

#showBalances

Displays an iframe that displays the user’s token balances from the currently connected network.

#Arguments

  • None

#Returns

  • Promise which resolves when the user closes the window

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08await magic.wallet.showBalances()

#showNFTs

Displays an iframe that shows the user’s NFTs in both an aggregated and detailed individual view. Supported only on Ethereum and Polygon. Ensure this is enabled in your developer dashboard via the ‘Widget UI’ tab.

#Arguments

  • None

#Returns

  • Promise which resolves when the user closes the window

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08await magic.wallet.showNFTs()

#showSendTokensUI

Displays an iframe with UI to help the user transfer tokens from their account to another address.

#Arguments

  • None

#Returns

  • Promise which resolves when the user closes the window

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08await magic.wallet.showSendTokensUI()

#showOnRamp

Displays an iframe modal with various on ramp providers for the user to purchase crypto from directly to their wallet.

To use the fiat on ramp for Dedicated Wallet apps, you will need to contact us to KYB with the payment provider prior to use. Once approved, ensure this toggle is enabled in your developer dashboard via the ‘Widget UI’ tab.

#Arguments

  • None

#Returns

  • Promise which resolves when the user closes the window

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08await magic.wallet.showOnRamp()

#getProvider

This method is introduced in [email protected] and must be used to get the current provider if third party wallets are enabled. If not using third party wallets, we suggest using magic.rpcProvider.

#Arguments

  • None

#Returns

  • Object: The rpc provider of the wallet a user is currently logged in with (MetaMask, Coinbase Wallet or Magic)

Important: To ensure rpc requests are routed to the correct wallet, developers must re-fetch the provider object using getProvider() and re-initialize the web3.js or ethers.js instance any time a user logs in, logs out, or disconnects their wallet.

#Web3.js/Ethers.js

Web3.js
Ethers.js
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05import Web3 from 'web3';
06
07const magic = new Magic('PUBLISHABLE_API_KEY', { 
08  network: "goerli",
09});
10
11const provider = await magic.wallet.getProvider();
12
13const web3 = new Web3(provider);
14
15const accounts = await magic.wallet.connectWithUI();
16
17// Listen for events
18web3.currentProvider.on('accountsChanged', handleAccountsChanged);
19web3.currentProvider.on('chainChanged', handleChainChanged);

#User Module

The User Module and it's members are accessible on the Magic SDK instance by the user property.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08magic.user;
09magic.user.getIdToken;
10magic.user.generateIdToken;
11magic.user.getInfo;
12magic.user.isLoggedIn;
13magic.user.logout;
14magic.user.showSettings;
15magic.user.requestInfoWithUI;

#getIdToken

Generates a Decentralized Id Token which acts as a proof of authentication to resource servers.

note

Only available with Dedicated Wallet.

#Arguments

  • lifespan? (Number): Will set the lifespan of the generated token. Defaults to 900s (15 mins).

#Returns

  • PromiEvent<string>: Base64-encoded string representation of a JSON tuple representing

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// Assumes a user is already logged in
09try {
10  const idToken = await magic.user.getIdToken();
11} catch {
12  // Handle errors if required!
13}

#generateIdToken

Generates a Decentralized ID token with optional serialized data.

note

Only available with Dedicated Wallet.

#Arguments

  • lifespan? (Number): Will set the lifespan of the generated token. Defaults to 900s (15 mins).
  • attachment? (String): Will set a signature of serialized data in the generated token. Defaults to "none".

#Returns

  • PromiEvent<string>: Base64-encoded string representation of a JSON tuple representing [proof, claim]

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// Assumes a user is already logged in
09try {
10  const idToken = await magic.user.generateIdToken({ attachment: 'SERVER_SECRET' });
11} catch {
12  // Handle errors if required!
13}

#getInfo

Retrieves information for the authenticated user.

#Arguments

  • None

#Returns

  • PromiEvent<string>:
    • issuer (String): The Decentralized ID of the user. In server-side use-cases, we recommend this value to be used as the user ID in your own tables.
    • email (String): Email address of the authenticated user
    • phoneNumber (String): The phone number of the authenticated user
    • publicAddress (String): The authenticated user's public address (a.k.a.: public key)
    • walletType (String): Information about the wallet the user is currently signed in with ('magic' | 'metamask' | 'coinbase_wallet')
    • isMfaEnabled (Boolean): Whether or not multi-factor authentication is enabled for the user
    • recoveryFactors (Array): Any recovery methods that have been enabled (ex. [{ type: 'phone_number', value: '+99999999' }])
note

When calling this method while connected with a 3rd party wallet (MetaMask, Coinbase Wallet), only the walletType will be returned.

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// Assumes a user is already logged in
09try {
10  const userInfo = await magic.user.getInfo();
11} catch {
12  // Handle errors if required!
13}

#isLoggedIn

Checks if a user is currently logged in to the Magic SDK.

#Arguments

  • None

#Returns

  • PromiEvent<boolean>

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  const isLoggedIn = await magic.user.isLoggedIn();
10  console.log(isLoggedIn); // => `true` or `false`
11} catch {
12  // Handle errors if required!
13}

#logout

Logs out the currently authenticated Magic user

#Arguments

  • None

#Returns

  • PromiEvent<boolean>

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await m.user.logout();
10  console.log(await magic.user.isLoggedIn()); // => `false`
11} catch {
12  // Handle errors if required!
13}

#showSettings

Displays an iframe with the current user’s settings. Allows for users to update their email address, enable multi-factor authentication, and add a recovery factor.

note

Only available with Dedicated Wallet. Access to MFA and account recovery require paid add-ons.

#Arguments

  • page? (String): Optional argument to deeplink to a specific page ('mfa' | 'update-email' | 'recovery')

#Returns

  • Promise which resolves when the user closes the window

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08try {
09  await magic.user.showSettings();
10} catch {
11  // Handle errors if required!
12}
13
14// Deeplink to MFA view
15try {
16  await magic.user.showSettings({ page: 'mfa' });
17} catch {
18  // Handle errors if required!
19}

#requestInfoWithUI

restricted availability

Universal wallets will soon be merged with Dedicated Wallets into a single product line. Universal apps created before February 7, 2024 will work as expected with no change. See our blog post to learn more.

Displays the wallet widget within an iframe that prompts the user to consent to sharing information with the requesting dApp with OpenID profile scopes. Currently, the only profile scope that can be requested is a verified email. Collecting a verified email address from third-party wallet users (MetaMask, Coinbase Wallet, etc.) is a premium feature but included in the free trial period (see pricing). User must be signed in for this method to return or else it will throw an error.

note

Only available with Universal Wallet.

#Arguments

  • scope? (Object): The object containing requested OpenID profile scopes.
    • email?: String : If the user should be prompted to provide them email as a required or optional field

#Returns

  • A promise which returns an Object: Contains result of the requested scopes
    • email?: String: The email of the user if they consented to providing it in the UI

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06// after user has already logged in
07const userInfo = await magic.user.requestInfoWithUI({ scope: { email: "required" }})
08console.log(userInfo.email); // the user's email if they consented.

#onUserLoggedOut

When the useStorageCache is enabled, there might be situations where the isLoggedIn function returns true despite the user being logged out. In such instances, an event will be emitted after a few milliseconds, providing an opportunity to manage the user's logged-out state, such as when a session expires.

note

Only necessary with when the useStorageCache option is set to true.

#Arguments

  • callback ((isLoggedOut: boolean) => void): The callback function when the event is emitted

#Returns

  • A function that can be called to unsubscribe from the event

#Example

Javascript
01import { Magic } from "magic-sdk"
02
03// Create Magic instance with useStorageCache set to true
04const magic = new Magic('PUBLISHABLE_API_KEY', {
05  useStorageCache: false
06});
07
08magic.user.onUserLoggedOut((isLoggedOut: boolean) => {
09  // Do something when user is logged out
10  navigation.navigate('LoginScreen')
11})

#OAuth Module

The OAuth Module and it's members are accessible on the Magic SDK instance by the oauth property.

To use the OAuth Module in your application, install @magic-ext/oauth along with magic-sdk.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03import { OAuthExtension } from "@magic-ext/react-native-bare-oauth";
04// Expo React Native
05import { Magic } from '@magic-sdk/react-native-expo';
06import { OAuthExtension } from "@magic-ext/react-native-expo-oauth";
07
08const magic = new Magic('PUBLISHABLE_API_KEY', {
09  extensions: [new OAuthExtension()],
10});
11
12magic.oauth;
13magic.oauth.loginWithPopup;

#loginWithPopup

Starts the OAuth 2.0 login flow.

note

Only available with Dedicated Wallet.

#Arguments

  • provider (String): The OAuth provider being used for login
  • redirectURI (String): A URL a user is sent to after they successfully log in
  • scope? (Array): Defines the specific permissions an application requests from a user

#Returns

  • None

#Valid Providers

NameArgument

Google

'google'

Facebook

'facebook'

Twitter

'twitter'

Apple

'apple'

Discord

'discord'

GitHub

'github'

LinkedIn

'linkedin'

Bitbucket

'bitbucket'

GitLab

'gitlab'

Twitch

'twitch'

Microsoft

'microsoft'

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03import { OAuthExtension } from "@magic-ext/react-native-bare-oauth";
04// Expo React Native
05import { Magic } from '@magic-sdk/react-native-expo';
06import { OAuthExtension } from "@magic-ext/react-native-expo-oauth";
07
08const magic = new Magic('PUBLISHABLE_API_KEY', {
09  extensions: [new OAuthExtension()],
10});
11
12await magic.oauth.loginWithPopup({
13  provider: '...' /* 'google', 'facebook', 'apple', etc. */,
14  redirectURI: 'https://your-app.com/your/oauth/callback',
15  scope: ['user:email'] /* optional */,
16});

#NFT Module

The NFT Module and it's members are accessible on the Magic SDK instance by the nft property.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08magic.nft;
09⁠magic.nft.checkout;
10magic.nft.purchase;
11magic.nft.transfer;

#checkout

Initiates an NFT Checkout using PayPal, allowing users to use Fiat currency to purchase NFTs.

#Arguments

  • contractId (String): The ID from Magic identifing the Smart Contract. This ID will be sent to you by your Magic Customer Success representative.
  • name (String): The name of the contract or NFT used in the Checkout UI to tell the user what they are purchasing
  • imageUrl (String): A URL for the NFT image that will be shown to the user in the UI. For NFTs revealed after purchase, you may use any placeholder image.
  • tokenId (String): The ID of the token to transfer. For ERC721 contracts, use tokenId = "0".
  • quantity? (Number): Number of tokens the user will purchase. If not provided, quantity will be 1.
  • walletAddress? (String): The on-chain address of the user's wallet, where the NFT will be delivered after purchase and minting. If not provided, the user's Magic Wallet address will be used.

#Returns

  • PromiEvent<boolean>: The promise resolves with a true boolean value if the purchase is successful and rejects with a specific error code if the request fails

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// Initiates the flow to purchase an NFT.
09try {
10  ...
11  /* Assuming user is logged in */
12  await magic.nft.checkout({
13    contractId: "abcd-efgh-1111-2222",
14    name: "My NFT Drop",
15    imageUrl: "https://nft-cdn.alchemy.com/matic-mumbai/1234",
16    quantity: 1,
17    tokenId: "0",
18    walletAddress: "0xabcdefg",
19  });
20} catch {
21  // Handle errors if required!
22}

#purchase

Initiates a purchase of a specified NFT.

#Arguments

  • nft: This contains all of the NFT meta information
    • name (String): NFT name
    • imageUrl (String): NFT image URL
    • blockchainNftId (String): NFT ID
    • contractAddress (String): NFT smart contract address
    • network (String): Network name
    • platform (String): Platform name
    • type (String): Type
  • identityPrefill: This contains all of the user prefill meta information
    • firstName (String): The user's first name
    • lastName (String): The user's last name
    • emailAddress (String): The user's email address
    • dateOfBirth (String): The user's date of birth in YYYY-MM-DD format
    • phone (String): The user's phone number
    • address: This contains all of the user address meta information
      • street1 (String): The user's street address
      • street2 (String): Additional street address information
      • city (String): City of user address
      • regionCode (String): Region code for country subdivisions
      • postalCode (String): Postal code of user's address
      • countryCode (String): Country code of user's address

#Returns

  • PromiEvent<boolean>: The promise resolves with a true boolean value if the transfer is successful and rejects with a specific error code if the request fails

#transfer

Initiates a transfer of a specified NFT.

#Arguments

  • contractAddress (String): The on-chain address of the NFT Smart Contract that holds the NFT
  • tokenId (String): The ID of the token to transfer
  • quantity? (Number): Number of tokens to transfer. If not provided, defaults to 1 token and allows use to override in the Transfer UI.
  • recipient? (String): The on-chain address of the wallet or contract you want to send the NFT to. If not provided, user will input in the Transfer UI.

#Returns

  • PromiEvent<boolean>: The promise resolves with a true boolean value if the transfer is successful and rejects with a specific error code if the request fails

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08// Initiates the flow to transfer a user's NFT.
09try {
10  ...
11  /* Assuming user is logged in */
12  await magic.nft.transfer({
13    contractAddress: '0xABCD',
14    tokenId: 1,
15  });
16} catch {
17  // Handle errors if required!
18}

#OpenID Module

note

This module requires an enterprise agreement. For more details click here.

The OpenID Module and it's members are accessible on the Magic SDK instance by the openid property.

To use the OpenID Module in your application, install @magic-ext/oidc along with magic-sdk.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06import { OpenIdExtension } from '@magic-ext/oidc';
07
08const magic = new Magic('PUBLISHABLE_API_KEY', {
09  extensions: [new OpenIdExtension()],
10});
11
12magic.openid;
13magic.openid.loginWithOIDC;

#loginWithOIDC

Authenticate users via your preferred OIDC client.

note

Only available with Dedicated Wallet.

#Arguments

  • jwt (String): The OIDC token from your identity provider
  • providerId (String): An alphanumeric ID provided by Magic after successful configuration of your identity provider

#Returns

  • PromiEvent<string | null>: The promise resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

#Example

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06import { OpenIdExtension } from '@magic-ext/oidc';
07
08const magic = new Magic('PUBLISHABLE_API_KEY', {
09  extensions: [new OpenIdExtension()],
10});
11
12const DID = await magic.openid.loginWithOIDC({
13  // this oidcToken comes from the identity provider
14  jwt: oidcToken,
15  // this providerId is provided by Magic
16  providerId: myProviderId,
17});

#Response and Error Handling

There are three types of error class to be aware of when working with Magic's client-side JavaScript SDK:

  • SDKError: Raised by the SDK to indicate missing parameters, communicate deprecation notices, or other internal issues. A notable example would be a MISSING_API_KEY error, which informs the required API key parameter was missing from new Magic(...).
  • RPCError: Errors associated with specific method calls to the Magic <iframe> context. These methods are formatted as JSON RPC 2.0 payloads, so they return error codes as integers. This type of error is raised by methods like AuthModule.loginWithMagicLink.
  • ExtensionError: Errors associated with method calls to Magic SDK Extensions. Extensions are an upcoming/experimental feature of Magic SDK. More information will be available once Extensions are officially released.

#SDKError

The SDKError class is exposed for instanceof operations.

Javascript
01// Bare React Native
02import { SDKError } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { SDKError } from '@magic-sdk/react-native-expo';
05
06try {
07  // Something async...
08catch (err) {
09  if (err instanceof SDKError) {
10    // Handle...
11  }
12}

SDKError instances expose the code field which may be used to deterministically identify the error. Additionally, an enumeration of error codes is exposed for convenience and readability:

Javascript
01// Bare React Native
02import { SDKErrorCode } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { SDKErrorCode } from '@magic-sdk/react-native-expo';
05
06SDKErrorCode.MissingApiKey;
07SDKErrorCode.ModalNotReady;
08SDKErrorCode.MalformedResponse;
09// and so forth...
10// Please reference the `Enum Key` column of the error table below.

#Error Codes

Enum KeyDescription
MissingApiKeyIndicates the required Magic API key is missing or invalid.
ModalNotReadyIndicates the Magic iframe context is not ready to receive events. This error should be rare and usually indicates an environmental issue or improper async/await usage.
MalformedResponseIndicates the response received from the Magic iframe context is malformed. We all make mistakes (even us), but this should still be a rare exception. If you encounter this, please be aware of phishing!
InvalidArgumentRaised if an SDK method receives an invalid argument. Generally, TypeScript saves us all from simple bugs, but there are validation edge cases it cannot solve—this error type will keep you informed!
ExtensionNotInitializedIndicates an extension method was invoked before the Magic SDK instance was initialized. Make sure to access extension methods only from the Magic SDK instance to avoid this error.

IncompatibleExtensions

One or more extensions you are trying to use are incompatible with the SDK being used.

#RPCError

The RPCError class is exposed for instanceof operations:

Javascript
01// Bare React Native
02import { RPCError } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { RPCError } from '@magic-sdk/react-native-expo';
05
06try {
07  // Something async...
08catch (err) {
09  if (err instanceof RPCError) {
10    // Handle...
11  }
12}

RPCError instances expose the code field which may be used to deterministically identify the error. Additionally, an enumeration of error codes is exposed for convenience and readability:

Javascript
01// Bare React Native
02import { RPCErrorCode } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { RPCErrorCode } from '@magic-sdk/react-native-expo';
05
06RPCErrorCode.MagicLinkExpired;
07RPCErrorCode.UserAlreadyLoggedIn;
08RPCErrorCode.ParseError;
09RPCErrorCode.MethodNotFound;
10RPCErrorCode.InternalError;
11// and so forth...
12// Please reference the `Enum Key` column of the error table below.

#Magic Link Error Codes

CodeEnum KeyDescription
-10000MagicLinkFailedVerificationThe magic link failed verification, possibly due to an internal service error or a generic network error.
-10001MagicLinkExpiredThe user clicked their magic link after it had expired (this can happen if the user takes more than 10 minutes to check their email).
-10002MagicLinkRateLimitedIf the showUI parameter is set to false, this error will communicate the email rate limit has been reached. Please debounce your method calls if this occurs.
-10006MagicLinkInvalidRedirectURLIf using the redirectURI parameter for the magic link flow, this error is recevied if the provided value is invalid for some reason.
-10003UserAlreadyLoggedInA user is already logged in. If a new user should replace the existing user, make sure to call logout before proceeding.
-10004UpdateEmailFailedAn update email request was unsuccessful, either due to an invalid email being supplied or the user canceled the action.
-10005UserRequestEditEmailThe user has stopped the login request because they want to edit the provided email.

-10010

InactiveRecipient

We were unable to deliver a Magic Link to the specified email address. The email address might be invalid.

-10011

AccessDeniedToUser

User denied account access.

-10015

RedirectLoginComplete

User has already completed authentication in the redirect window.

#Standard JSON RPC 2.0 Error Codes

CodeEnum KeyDescription
-32700ParseErrorInvalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
-32600InvalidRequestThe JSON sent is not a valid Request object.
-32601MethodNotFoundThe method does not exist / is not available.
-32602InvalidParamsInvalid method parameter(s).
-32603InternalErrorInternal JSON-RPC error. These can manifest as different generic issues (i.e.: attempting to access a protected endpoint before the user is logged in).

#ExtensionError

The ExtensionError class is exposed for instanceof operations:

Bare
Expo
01import { ExtensionError } from '@magic-sdk/react-native-bare';
02
03try {
04  // Something async...
05catch (err) {
06  if (err instanceof ExtensionError) {
07    // Handle...
08  }
09}

ExtensionError instances expose the code field which may be used to deterministically identify the error. Magic SDK does not export a global enumeration of Extension error codes. Instead, Extension authors are responsible for exposing and documenting error codes relevant to the Extension's use-case.

#PromiEvents

Magic SDK provides a flexible interface for handling methods which encompass multiple "stages" of an action. Promises returned by Magic SDK resolve when a flow has reached finality, but certain methods also contain life-cycle events that dispatch throughout. We refer to this interface as a PromiEvent. There is prior art to inspire this approach in Ethereum's Web3 standard.

PromiEvent is a portmanteau of Promise and EventEmitter. Browser and React Native SDK methods return this object type, which is a native JavaScript Promise overloaded with EventEmitter methods. This value can be awaited in modern async/await code, or you may register event listeners to handle method-specific life-cycle hooks. Each PromiEvent contains the following default event types:

  • "done": Called when the Promise resolves. This is equivalent to Promise.then.
  • "error": Called if the Promise rejects. This is equivalent to Promise.catch.
  • "settled": Called when the Promise either resolves or rejects. This is equivalent to Promise.finally.

Look for additional event types documented near the method they relate to. Events are strongly-typed by TypeScript to offer developer hints and conveniant IDE auto-complete.

Bare
Expo
01import { Magic } from '@magic-sdk/react-native-bare';
02
03const req = magic.auth.loginWithMagicLink({ email: '[email protected]' });
04
05req
06  .on('email-sent', () => {
07    /* ... */
08  })
09  .then(DIDToken => {
10    /* ... */
11  })
12  .once('email-not-deliverable', () => {
13    /* ... */
14  })
15  .catch(error => {
16    /* ... */
17  })
18  .on('error', error => {
19    /* ... */
20  });

#Usage

#EVM RPC Methods

Magic supports the following EVM RPC Methods that can be called through a web3 provider library such as web3.js or ethers.js.

Note: starting from [email protected], eth_accounts will return an empty array if no user is logged in, instead of prompting the login form. To prompt the login form, use connectWithUI().

  • eth_accounts
  • get_balance
  • eth_estimateGas
  • eth_gasPrice
  • eth_sendTransaction
  • personal_sign
  • eth_signTypedData_v3
  • eth_signTypedData_v4

#SafeAreaView

As of v14.0.0 our React Native package offerings wrap the <magic.Relayer /> in react-native-safe-area-context's <SafeAreaView />. To prevent any adverse behavior in your app, please place the Magic iFrame React component at the root view of your application wrapped in a SafeAreaProvider as described in the documentation.

We have also added an optional backgroundColor prop to the Relayer to fix issues with SafeAreaView showing the background. By default, the background will be white. If you have changed the background color as part of your custom branding setup, make sure to pass your custom background color to magic.Relayer:

Javascript
01<magic.Relayer backgroundColor="#0000FF"/>

#Handle internet connection problems

When an app is opened without an internet connection, any request to the Magic SDK will result in a rejection with a MagicSDKError:

Javascript
01{
02  "code": "MODAL_NOT_READY",
03  "rawMessage": "Modal is not ready."
04}

It's good practice to use @react-native-community/netinfo to track the internet connection state of the device. For your convenience, we've also added a hook that uses this library behind the scenes:

Javascript
01import { useInternetConnection } from '@magic-sdk/react-native-expo';
02
03export default function App() {
04  const magic = new Magic('PUBLISHABLE_API_KEY');
05
06  const connected = useInternetConnection()
07
08  useEffect(() => {
09    if (!connected) 
10      {// Unmount this component and show your "You're offline" screen.}
11  }, [connected])
12
13  return <>
14    <SafeAreaProvider>
15      {/* Render the Magic iframe! */}
16      <magic.Relayer />
17      {...}          
18    </SafeAreaProvider>
19  </>
20}

#Re-authenticate Users

A user's Magic SDK session persists up to 7 days by default, so re-authentication is usually frictionless.

Note: the session length is customizable by the developer through the Magic dashboard.

Before re-authenticating a user, install the Magic Client SDK​.

Javascript
01// Bare React Native
02import { Magic } from '@magic-sdk/react-native-bare';
03// Expo React Native
04import { Magic } from '@magic-sdk/react-native-expo';
05
06const magic = new Magic('PUBLISHABLE_API_KEY');
07
08const email = '[email protected]';
09
10if (await magic.user.isLoggedIn()) {
11  const didToken = await magic.user.getIdToken();
12
13  // Do something with the DID token.
14  // For instance, this could be a `fetch` call
15  // to a protected backend endpoint.
16} else {
17  // Log in the user
18  const user = await magic.auth.loginWithMagicLink({ email });
19}

#Resources