Skip to main content

Getting Started

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

Installation

To use Magic in your application, install the magic-sdk dependency.
NOTE⁠If you’re integrating with OAuth, additional dependencies are needed. You’ll find the installation instructions in its dedicated section within this documentation.

Constructor

Magic() Configure and construct your Magic SDK instance.

Initialization

JavaScript

Global Methods

Global methods and properties are accessible on the Magic SDK instance itself.

preload

Starts downloading the static assets required to render the Magic iframe context.
NOTEAs of magic-sdk version 21.0.0, the SDK constructor will preload the iframe’s static assets by default, unless the deferPreload flag is passed into the constructor options. See Release Notes
JavaScript

Auth Module

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

loginWithEmailOTP

Authenticate a user passwordlessly using an email one-time code sent to the specified user’s email address. Arguments
  • email (String): The user email to log in with
  • lifespan? (Number): Set the lifespan of the resolved Decentralize ID token. Defaults to 900s (15 mins)
  • showUI? (Boolean): If true, show an out-of-the-box UI to accept the OTP from user. Defaults to true
  • 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 false value only takes effect when you have also set showUI: false. If you enable Device Verification in the Magic Dashboard and are passing showUI: false you must also explicitly pass deviceCheckUI: false
Available from [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
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:
JavaScript
Event Enums Email OTP Device Verification 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

loginWithSMS

Authenticate a user passwordlessly using a one-time code sent to the specified phone number. List of Currently Blocked Country Codes Arguments
  • phoneNumber (String): E.164 formatted phone number
  • lifespan? (Number): Set the lifespan of the resolved Decentralize ID token. Defaults to 900s (15 mins)
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
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

updateEmailWithUI

Initiates the update email flow that allows a user to change their email address. 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
Event Handling A white-label update email flow is available when passing showUI: false to this method. The white-label flow is only supported in Magic SDK v22.0.0 and above. Here’s a short example to illustrate listening for and emitting events during the flow:
JavaScript
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

Wallet Module

The Wallet Module and it’s members are accessible on the Magic SDK instance by the wallet property.
The Wallet Module is currently only compatible with Ethereum, Polygon, Base, Arbitrum, Optimism, and Flow (no NFTs).

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

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. 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

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

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

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

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

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 onramp, 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

sign7702Authorization

Signs an EIP-7702 authorization that delegates your EOA to a smart contract implementation. This authorization can then be included in a Type-4 transaction via send7702Transaction.
Available as of [email protected]. See the EIP-7702 feature guide for a complete walkthrough.
Arguments
  • contractAddress (String): The smart contract implementation address to delegate to
  • chainId (Number): The chain ID for the authorization
  • nonce? (Number): The account nonce. If omitted, fetched from the network automatically
Returns
  • Promise<object>:
    • contractAddress (String): The contract address that was authorized
    • chainId (Number): The chain ID for the authorization
    • nonce (Number): The nonce used in the authorization
    • v (Number): The v component of the signature (27 or 28)
    • r (String): The r component of the signature
    • s (String): The s component of the signature
Example
JavaScript

send7702Transaction

Sends a Type-4 (EIP-7702) transaction that includes signed authorizations. This executes the delegation on-chain.
Available as of [email protected]. See the EIP-7702 feature guide for a complete walkthrough.
Arguments
  • to (String): The recipient address
  • authorizationList (Array): Array of signed authorizations returned by sign7702Authorization
  • value? (String): Value to send in wei (hex string). Defaults to '0x0'
  • data? (String): Transaction calldata. Defaults to '0x'
  • gas? (String): Gas limit (hex string). If omitted, estimated automatically
  • gasLimit? (String): Alias for gas
  • maxFeePerGas? (String): Max fee per gas (hex string). If omitted, fetched from the network
  • maxPriorityFeePerGas? (String): Max priority fee per gas (hex string). If omitted, fetched from the network
  • nonce? (Number): Transaction nonce. If omitted, fetched from the network
Returns
  • Promise<object>:
    • transactionHash (String): The hash of the submitted transaction
Example
JavaScript

User Module

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

getIdToken

Generates a Decentralized Id Token which acts as a proof of authentication to resource servers. 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 [proof, claim]
Example
JavaScript

generateIdToken

Generates a Decentralized ID token with optional serialized data. 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

getInfo

Retrieves information for the authenticated user.
Breaking Change Notice: Starting with SDK v30.0.0, the publicAddress field has been removed from the response and replaced with the structured wallets object. Please see the response structure below for more details.
Arguments
  • None
Returns The response structure depends on your SDK version:
Response with Wallets Object
  • PromiEvent<object>:
    • 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
    • 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' }])
    • wallets (Object): Organized wallet addresses by blockchain and network:
      • [chainName] (Object): Each supported blockchain (e.g., ethereum, solana, hedera)
        • publicAddress (String | null): The mainnet public address for this chain, or null if no mainnet wallet exists
        • subAccounts (Array): Additional network addresses for this chain
          • name (String): Network name (e.g., testnet)
          • publicAddress (String): Public address for this network
Example Response:
Example
JavaScript

isLoggedIn

Checks if a user is currently logged in to the Magic SDK. Arguments
  • None
Returns
  • PromiEvent<boolean>
Example
JavaScript

logout

Logs out the currently authenticated Magic user Arguments
  • None
Returns
  • PromiEvent<boolean>
Example
JavaScript

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.
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
Whitelabel Whitelabel the flow starting from where the user needs to add a recovery factor phone number. This allows you to implement your own UI, but you will need to implement some custom event handling according to your needs. Access to account recovery require paid add-ons. Arguments
  • page (String): 'recovery'
  • showUI (Boolean): false
Returns
  • Promise which resolves when the user closes the window
Example
JavaScript

recoverAccount

A user can recover their email account if they’ve setup a phone number as a recovery factor. Calling this method will display a modal for the user to submit the sent SMS OTP. Access to account recovery require paid add-ons. Arguments
  • email (String): The email address (primary auth factor) of the user
Returns
  • PromiEvent<boolean>: The promise resolves with a true boolean value if the recovery is successful and rejects if the request fails
Example
JavaScript

enableMFA

Displays an iframe deep linked to the beginning of the enable MFA flow. This is the same as calling showSettings({ page: 'mfa' })
Access to MFA require paid add-ons. Available as of magic-sdk v28.11.0
Arguments
  • showUI? (Boolean): If true, show an out-of-the-box UI to take user through flow to enable MFA. Defaults to true
Returns
  • Promise which resolves when the user closes the window
Example
JavaScript
Events

disableMFA

Displays an iframe deep linked to the beginning of the disable MFA flow. This method assumes MFA has been enabled for the logged in user. This cannot be achieved by calling showSettings() . Access to MFA require paid add-ons. Available as of magic-sdk v28.11.0 Arguments
  • showUI? (Boolean): If true, show an out-of-the-box UI to take user through flow to disable MFA. Defaults to true
Returns
  • Promise which resolves when the user closes the window
Example
JavaScript
Events

revealEVMPrivateKey

Displays an iframe revealing the current user’s EVM 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.
Breaking Change: As of SDK version 31.0.0, revealPrivateKey() has been renamed to revealEVMPrivateKey() for EVM chains. For non-EVM chains, use the specific extension’s revealPrivateKey() method instead.
Arguments
  • None
Returns
  • Promise which resolves when the user closes the window
Example
JavaScript

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
JavaScript

OAuth Module

The OAuth Module and it’s members are accessible on the Magic SDK instance by the oauth2 property. To use the OAuth Module in your application, install @magic-ext/oauth2 along with magic-sdk.

loginWithRedirect

Starts the OAuth 2.0 login flow. 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 Example
JavaScript

getRedirectResult

Returns the final OAuth 2.0 result. Arguments
  • lifespan? (Number): Set the lifespan of the resolved Decentralize ID token. Defaults to 900s (15 mins)
Returns
  • PromiEvent<object>:
    • magic (Object): Information about the authenticated Magic user. Comprised of idToken and userMetadata.
    • oauth (Object): Information about the authenticated OAuth user. Comprised of accessToken, provider, scope, userHandle, and userInfo.
Example
JavaScript
The shape of magic.userMetadata (typed as MagicUserMetadata) differs by SDK version. On SDK v30.0.0+, wallet addresses are nested under a wallets object — access the Ethereum address via result.magic.userMetadata.wallets?.ethereum?.publicAddress. On SDK v29.x and below, the address is available as a flat field: result.magic.userMetadata.publicAddress. See the getInfo method above for the full response shapes of each version.

Smart Account Module

The Smart Account Module and its members are accessible on the Magic SDK instance by the smartAccount property. To use the Smart Account Module in your application, install @magic-ext/smart-account along with magic-sdk.
For more detailed information, see the Smart Account documentation.

sendTransaction

Sends one or more calls through an EIP-7702 smart account via Alchemy’s Smart Wallet infrastructure. Arguments
  • params (Object):
    • chainId (Number): The chain ID for the transaction
    • calls (Array): Array of call objects, each containing:
      • to (String): The recipient or contract address
      • data (String, optional): Encoded calldata
      • value (String, optional): Value to send in wei
Returns
  • Promise<{ id: string; transactionHash: string | undefined; chainId: number; }>: Resolves with the call bundle ID, transaction hash, and chain ID
Example
JavaScript

EVM Module

The EVM Module and it’s members are accessible on the Magic SDK instance by the evm property. To use the EVM Module in your application, install @magic-ext/evm along with magic-sdk.

switchChain

Switches the active EVM chain to the specified chain ID.
For more detailed information, see the EVM Chain Switching documentation.
Arguments
  • chainId (Number): The chain ID of the target EVM network
Returns
  • Promise<{ network: string | { rpcUrl: string; chainId?: number; chainType?: string; } | undefined; }>: Resolves with network configuration when the network switch is complete
Example
JavaScript

Blockchain Modules

Magic SDK provides blockchain-specific modules for various networks through extensions.

Available Blockchain Extensions

Common Methods

All blockchain extensions provide these common methods:

getPublicAddress

Retrieves the public address for the specific blockchain network. Arguments
  • None
Returns
  • Promise<string>: The public address for the blockchain network
Example
JavaScript

revealPrivateKey

Displays an iframe revealing the private key for the specific blockchain network. This method shows a secure interface where users can view and copy their private key. Arguments
  • None
Returns
  • Promise<void>: Resolves when the user closes the private key display window
Example
JavaScript

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
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

Error Codes

RPCError

The RPCError class is exposed for instanceof operations:
JavaScript
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

Magic Error Codes

Standard JSON RPC 2.0 Error Codes

ExtensionError

The ExtensionError class is exposed for instanceof operations:
JavaScript
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.
JavaScript

EVM RPC Methods

Magic supports the following EVM RPC Methods that can be called through a web3 provider library such as 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

Examples

Re-authenticate Users

A user’s Magic SDK session persists up to 7 days by default, so re-authentication is usually friction-less. Note: the session length is customizable by the developer through the Magic Dashboard. Before re-authenticating a user, install the Magic Client SDK​.
JavaScript

Resources

Versions

All changes to the SDK are covered in our latest release notes.