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.
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
08pod install
09
10# Start your app
11cd /path/to/project/root
12yarn start
13
#Constructor
#Magic()
Configure and construct your Magic SDK instance.
Parameter | Type | Definition |
| String | Your publishable API Key retrieved from the Magic Dashboard. |
| String | Customize the language of Magic's modal, email and confirmation screen. See Localization for more. |
| String | Object | (String): A representation of the connected Ethereum network (mainnet or goerli). (Object): A custom Ethereum Node configuration with the following shape: |
| String | A URL pointing to the Magic |
| 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. |
| Boolean | An optional flag to allow the usage of the local storage as cache. Currently it is only used for faster calls to |
#Initialization
Initialize Magic instance.
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 tomagic.Relayer
.
#Example
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.
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.updateEmailWithUI;
#loginWithEmailOTP
Authenticate a user passwordlessly using an email one-time code sent to the specified user's email address.
Only available with Dedicated Wallet.
#Arguments
email
(String): The user email to log in withshowUI?
(Boolean): Iftrue
, show an out-of-the-box UI to accept the OTP from user. Defaults totrue
.deviceCheckUI?
(Boolean): The default value istrue
. It shows Magic branded UI securing sign-ins from new devices. If set tofalse
, the UI will remain hidden. However, this the false value only takes effect when you have also set theshowUI: false
. Available sincemagic-sdk@19.1.0
.
#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
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: 'hello@example.com' });
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: 'hello@example.com', showUI: false });
18} catch {
19 // Handle errors if required!
20}
#Event Handling
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:
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: "hello@example.com", 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 Name | Definition |
email-otp-sent | Dispatched when the OTP email has been successfully sent from the Magic server. |
verify-email-otp | Emit along with the OTP to verify the code from user. |
invalid-email-otp | Dispatched when the OTP sent fails verification. |
| Emit to cancel the login request. |
Device Verification
Event Name | Definition |
device-needs-approval | Dispatched when the device is unrecognized and requires user approval |
device-verification-email-sent | Dispatched when the device verification email is sent |
device-approved | Dispatched when the user has approved the unrecongized device |
| Dispatched when the email verification email has expired |
| 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:
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: 'hello@example.com' });
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
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
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
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:
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}
#updateEmailWithUI
Initiates the update email flow that allows a user to change their email address.
Only available with Dedicated Wallet.
#Arguments
email
(String): The new email to update toshowUI?
(Boolean): Iftrue
, 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
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: 'new_user_email@example.com' });
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: 'new_user_email@example.com', showUI: false });
24} catch {
25 // Handle errors if required!
26}
#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:
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: 'hello@example.com', 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 Name | Definition |
new-email-confirmed | Dispatched when the magic link has been clicked from the user’s new email address. |
email-sent | Dispatched when the magic link email has been successfully sent from the Magic Link server to the user’s new email address. |
email-not-deliverable | Dispatched 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. |
retry | Dispatched 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.
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 anString[]
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
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 |
| 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
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
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
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
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
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
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 magic-sdk@17.0.0
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
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.
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.revealPrivateKey;
16magic.user.requestInfoWithUI;
#getIdToken
Generates a Decentralized Id Token which acts as a proof of authentication to resource servers.
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
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.
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
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 userphoneNumber
(String): The phone number of the authenticated userpublicAddress
(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 userrecoveryFactors
(Array): Any recovery methods that have been enabled (ex.[{ type: 'phone_number', value: '+99999999' }]
)
When calling this method while connected with a 3rd party wallet (MetaMask, Coinbase Wallet), only the walletType
will be returned.
#Example
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
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
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.
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
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}
#revealPrivateKey
Displays an iframe revealing the current user’s private key. Allows for users to take their private key to another wallet. Neither Magic nor the developer can see this key; only the end user can.
Only available with Dedicated Wallet.
#Arguments
- None
#Returns
Promise
which resolves when the user closes the window
#Example
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.revealPrivateKey();
10} catch {
11 // Handle errors if required!
12}
#requestInfoWithUI
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.
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 arequired
oroptional
field
#Returns
- A
promise
which returns anObject
: Contains result of the requested scopesemail?: String
: The email of the user if they consented to providing it in the UI
#Example
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.
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
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
.
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.
Only available with Dedicated Wallet.
#Arguments
provider
(String): The OAuth provider being used for loginredirectURI
(String): A URL a user is sent to after they successfully log inscope?
(Array): Defines the specific permissions an application requests from a user
#Returns
- None
#Valid Providers
Name | Argument |
| |
| |
| |
Apple |
|
Discord |
|
GitHub |
|
| |
Bitbucket |
|
GitLab |
|
Twitch |
|
Microsoft |
|
#Example
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});
#OpenID Module
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
.
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.
Only available with Dedicated Wallet.
#Arguments
jwt
(String): The OIDC token from your identity providerproviderId
(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
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 aMISSING_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 likeauth.loginWithEmailOTP
.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.
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:
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 Key | Description |
MissingApiKey | Indicates the required Magic API key is missing or invalid. |
ModalNotReady | Indicates 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. |
MalformedResponse | Indicates 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! |
InvalidArgument | Raised 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! |
ExtensionNotInitialized | Indicates 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. |
| 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:
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:
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
Code | Enum Key | Description |
-10000 | MagicLinkFailedVerification | The magic link failed verification, possibly due to an internal service error or a generic network error. |
-10001 | MagicLinkExpired | The user clicked their magic link after it had expired (this can happen if the user takes more than 10 minutes to check their email). |
-10002 | MagicLinkRateLimited | If 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. |
-10006 | MagicLinkInvalidRedirectURL | If using the redirectURI parameter for the magic link flow, this error is recevied if the provided value is invalid for some reason. |
-10003 | UserAlreadyLoggedIn | A user is already logged in. If a new user should replace the existing user, make sure to call logout before proceeding. |
-10004 | UpdateEmailFailed | An update email request was unsuccessful, either due to an invalid email being supplied or the user canceled the action. |
-10005 | UserRequestEditEmail | The user has stopped the login request because they want to edit the provided email. |
-10010 |
| We were unable to deliver a Magic Link to the specified email address. The email address might be invalid. |
-10011 |
| User denied account access. |
-10015 |
| User has already completed authentication in the redirect window. |
#Standard JSON RPC 2.0 Error Codes
Code | Enum Key | Description |
-32700 | ParseError | Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. |
-32600 | InvalidRequest | The JSON sent is not a valid Request object. |
-32601 | MethodNotFound | The method does not exist / is not available. |
-32602 | InvalidParams | Invalid method parameter(s). |
-32603 | InternalError | Internal 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:
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 thePromise
resolves. This is equivalent toPromise.then
."error"
: Called if thePromise
rejects. This is equivalent toPromise.catch
."settled"
: Called when thePromise
either resolves or rejects. This is equivalent toPromise.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.
01import { Magic } from '@magic-sdk/react-native-bare';
02
03const req = magic.auth.loginWithEmailOTP({ email: 'hello@magic.link' });
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 magic-sdk@17.0.0
, 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
:
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
:
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:
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.
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 = 'example@magic.link';
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.loginWithEmailOTP({ email });
19}