Node API Reference

Node API Reference

#Constructor

#Arguments

new Magic(secretApiKey, options?)

  • secretApiKey (String): Your secret API Key retrieved from the Magic Dashboard.
  • options.endpoint?(String): A URL pointing to the Magic API. You should not need to provide this value except in case you are building highly custom integration tests.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02
03let m;
04
05// Construct with an API key:
06m = new Magic('API_KEY');
07
08// Construct with an API key plus options:
09m = new Magic('API_KEY', { endpoint: '...' });

#Token Module

The Token Module and its members are accessible on the Magic Admin SDK instance by the token property.

Typescript
01const { Magic } = require('@magic-sdk/admin');
02
03const mAdmin = new Magic('SECRET_API_KEY');
04
05mAdmin.token;
06mAdmin.token.getIssuer;
07mAdmin.token.getPublicAddress;
08mAdmin.token.decode;
09mAdmin.token.validate;

#getIssuer

#Arguments

getIssuer(didToken)

didToken (String): A Decentralized ID Token generated by a Magic user on the client-side.

#Returns

string: The Decentralized ID of the Magic User who generated the DID Token.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06/* Gets the DID token from a login request */
07app.get('/login', async (req: any, res: any) => {
08  /*
09    Assumes DIDToken was passed in the Authorization header
10    in the standard `Bearer {token}` format.
11   */
12  const DIDToken = req.headers.authorization.substring(7);
13  const issuer = mAdmin.token.getIssuer(DIDToken);
14  /* You can use this as the ID column in your own tables */
15});

#getPublicAddress

Gets the cryptographic public address of the Magic User who generated the supplied token.

#Arguments

getPublicAddress(didToken)

#Returns

string: The public address of the Magic User who generated the DID Token. Currently, this value is associated with the Ethereum blockchain.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06/* Gets the DID token from a login request */
07app.get('/login', async (req: any, res: any) => {
08  /*
09    Assumes DIDToken was passed in the Authorization header
10    in the standard `Bearer {token}` format.
11   */
12  const DIDToken = req.headers.authorization.substring(7);
13  const publicAddress = mAdmin.token.getPublicAddress(DIDToken);
14  /* You can use this as the ID column in your own tables */
15});

#decode

Decodes a Decentralized ID Token from a Base64 string into a tuple of its individual components.

#Arguments

decode(didToken)

#Returns

[string, Claim]: containing the [proof, claim] that composes the DID Token. The claim, while given as a JSON string, is automatically parsed to the following interface:

Typescript
01interface Claim {
02  iat: number; // Issued At Timestamp
03  ext: number; // Expiration Timestamp
04  iss: string; // Issuer of DID Token
05  sub: string; // Subject
06  aud: string; // Audience
07  nbf: number; // Not Before Timestamp
08  tid: string; // DID Token ID
09  add: string; // (optional) Misc additional signed data
10}

As a convenience, the above interface is available to your code in TypeScript:

Typescript
01import { Claim } from '@magic-sdk/admin';

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06/* Gets the DID token from a login request */
07app.get('/login', async (req: any, res: any) => {
08  /*
09    Assumes DIDToken was passed in the Authorization header
10    in the standard `Bearer {token}` format.
11   */
12  const DIDToken = req.headers.authorization.substring(7);
13  const [proof, claim] =  mAdmin.token.decode(DIDToken);
14
15  console.log(proof); // => string
16
17  console.log(claim);
18  /*
19    => {
20      iat: number,
21      ext: number,
22      iss: string,
23      sub: string,
24      aud: string,
25      nbf: number,
26      tid: string
27    }
28   */
29});

#validate

Validates a Decentralized ID token.

#Arguments

validate(didToken, attachment? = 'none')

  • didToken (String): A Decentralized ID Token generated by a Magic user on the client-side.
  • attachment? (String): Arbitrary, serialized data to be used for recovery of the add field on the Decentralized ID Token (Defaults to "none").

#Returns

void: The function will return if the specified DID token is authentic and not expired. If the token is forged or otherwise invalid, the function will throw a descriptive error.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06/* Gets the DID token from a login request */
07app.get('/login', async (req: any, res: any) => {
08  /*
09    Assumes DIDToken was passed in the Authorization header
10    in the standard `Bearer {token}` format.
11   */
12  const DIDToken = req.headers.authorization.substring(7);
13  mAdmin.token.validate(DIDToken);
14  /* User is logged in. Set cookies! */
15});

#User Module

#logoutByIssuer

Logs a user out of all client-side Magic SDK sessions given the user's Decentralized ID.

#Arguments

logoutByIssuer(issuer)

#Returns

Promise<void>

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Grabs user's Decentralized ID from the DID Token
07const issuer = mAdmin.token.getIssuer(DIDToken);
08
09// logs the user out of all valid browser sessions.
10await mAdmin.users.logoutByIssuer(issuer);

#logoutByPublicAddress

Logs a user out of all client-side Magic SDK sessions given the user's public address.

#Arguments

logoutByPublicAddress(publicAddress)

  • publicAddress (String): The user's Ethereum public address to log out via the Magic API.

#Returns

Promise<void>

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Grabs user's public address by DIDToken
07const userPublicAddress = mAdmin.token.getPublicAddress(DIDToken);
08
09// logs the user out of all valid browser sessions.
10await mAdmin.users.logoutByPublicAddress(userPublicAddress);

#logoutByToken

Logs a user out of all client-side Magic SDK sessions given the user's DID token.

#Arguments

logoutByToken(didToken)

#Returns

Promise<void>

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Get a token however you wish! Perhaps this is attached
07// to `req.authorization`
08const DIDToken = // ...
09
10// logs the user out of all valid browser sessions.
11await mAdmin.users.logoutByToken(DIDToken);

#getMetadataByIssuer

Retrieves information about user by the supplied "issuer".

#Arguments

getMetadataByIssuer(issuer)

#Returns

Promise<{ issuer, publicAddress, email, oauthProvider, phoneNumber }>: an object containing the issuer, cryptographic public address, email, OAuth provider, and phone number of the authenticated user. The value of the fields returned depend on the login method used.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
  • email (String | null): Email address of the authenticated user.
  • oauthProvider (String | null): OAuth of the authenticated user.
  • phoneNumber (String | null): Phone number of the authenticated user.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Grabs the issuer from a DID Token
07const issuer = mAdmin.token.getIssuer(DIDToken);
08
09// Gets user metadata based on the given issuer
10const metadata = await mAdmin.users.getMetadataByIssuer(issuer);

#getMetadataByPublicAddress

Retrieves information about user by the supplied public address.

#Arguments

getMetadataByPublicAddress(publicAddress)

#Returns

Promise<{ issuer, publicAddress, email, oauthProvider, phoneNumber }>: an object containing the issuer, cryptographic public address, email, OAuth provider, and phone number of the authenticated user. The value of the fields returned depend on the login method used.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
  • email (String | null): Email address of the authenticated user.
  • oauthProvider (String | null): OAuth of the authenticated user.
  • phoneNumber (String | null): Phone number of the authenticated user.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Grabs the issuer from a DID Token
07const userPublicAddress = mAdmin.token.getPublicAddress(DIDToken);
08
09// Gets user metadata based on the given issuer
10const metadata = await mAdmin.users.getMetadataByPublicAddress(userPublicAddress);

#getMetadataByToken

Retrieves information about user by the supplied DID Token.

#Arguments

getMetadataByToken(didToken)

#Returns

Promise<{ issuer, publicAddress, email, oauthProvider, phoneNumber }>: an object containing the issuer, cryptographic public address, email, OAuth provider, and phone number of the authenticated user. The value of the fields returned depend on the login method used.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
  • email (String | null): Email address of the authenticated user.
  • oauthProvider (String | null): OAuth of the authenticated user.
  • phoneNumber (String | null): Phone number of the authenticated user.

#Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Get a token however you wish! Perhaps this is attached
07// to `req.authorization`
08const DIDToken = // ...
09
10// Retrieves user information by DID token
11const metadata = await mAdmin.users.getMetadataByToken(DIDToken);

#Multichain Methods

The following multichain methods require the use of the enum WalletType that is exported from the Magic Admin SDK.

Typescript
01enum WalletType {
02  ETH = 'ETH',
03  HARMONY = 'HARMONY',
04  ICON = 'ICON',
05  FLOW = 'FLOW',
06  TEZOS = 'TEZOS',
07  ZILLIQA = 'ZILLIQA',
08  POLKADOT = 'POLKADOT',
09  SOLANA = 'SOLANA',
10  AVAX = 'AVAX',
11  ALGOD = 'ALGOD',
12  COSMOS = 'COSMOS',
13  CELO = 'CELO',
14  BITCOIN = 'BITCOIN',
15  NEAR = 'NEAR',
16  HELIUM = 'HELIUM',
17  CONFLUX = 'CONFLUX',
18  TERRA = 'TERRA',
19  TAQUITO = 'TAQUITO',
20  ED = 'ED',
21  HEDERA = 'HEDERA',
22  NONE = 'NONE',
23  ANY = 'ANY',
24}

#getMetadataByIssuerAndWallet

Retrieves information about user, including their multichain wallets, by the supplied issuer.

#Arguments

getMetadataByIssuerAndWallet(issuer, walletType)

#Returns

Promise<{ issuer, publicAddress, email, oauthProvider, phoneNumber, wallets }>: an object containing the issuer, cryptographic Ethereum public address, email, OAuth provider, phone number, and wallets of the authenticated user. The value of the fields returned depend on the login method used.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
  • email (String | null): Email address of the authenticated user.
  • oauthProvider (String | null): OAuth of the authenticated user.
  • phoneNumber (String | null): Phone number of the authenticated user.
  • wallets (Object[]): The multichain wallets of the authenticated user.

#Example

Typescript
01const { Magic, WalletType } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Grabs the issuer from a DID Token
07const issuer = mAdmin.token.getIssuer(DIDToken);
08
09// Gets user metadata based on the given issuer
10const metadata = await mAdmin.users.getMetadataByIssuerAndWallet(issuer, WalletType.ANY);

#getMetadataByPublicAddressAndWallet

Retrieves information about user, including their multichain wallets, by the supplied public address.

#Arguments

getMetadataByPublicAddressAndWallet(publicAddress, walletType)

  • publicAddress (String): The user's Ethereum public address, which can be parsed using TokenModule.getPublicAddress.
  • walletType ( WalletType ): The wallet type. Must import WalletType from Admin SDK.

#Returns

Promise<{ issuer, publicAddress, email, oauthProvider, phoneNumber, wallets }>: an object containing the issuer, cryptographic Ethereum public address, email, OAuth provider, phone number, and wallets of the authenticated user. The value of the fields returned depend on the login method used.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
  • email (String | null): Email address of the authenticated user.
  • oauthProvider (String | null): OAuth of the authenticated user.
  • phoneNumber (String | null): Phone number of the authenticated user.
  • wallets (Object[]): The multichain wallets of the authenticated user.

#Example

Typescript
01const { Magic, WalletType } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Grabs the publicAddress from a DID Token
07const userPublicAddress = mAdmin.token.getPublicAddress(DIDToken);
08
09// Gets user metadata based on the given public address
10const metadata = await mAdmin.users.getMetadataByPublicAddressAndWallet(publicAddress, WalletType.ANY);

#getMetadataByTokenAndWallet

Retrieves information about user, including their multichain wallets, by the supplied DID Token.

#Arguments

getMetadataByTokenAndWallet(didToken, walletType)

  • didToken (String): A valid Decentralized ID Token generated client-side by a Magic user.
  • walletType ( WalletType ): The wallet type. Must import WalletType from Admin SDK

#Returns

Promise<{ issuer, publicAddress, email, oauthProvider, phoneNumber, wallets }>: an object containing the issuer, cryptographic Ethereum public address, email, OAuth provider, phone number, and wallets of the authenticated user. The value of the fields returned depend on the login method used.

  • issuer (String): The Decentralized ID of the user. We recommend this value to be used as the user ID in your own tables.
  • publicAddress(String): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
  • email (String | null): Email address of the authenticated user.
  • oauthProvider (String | null): OAuth of the authenticated user.
  • phoneNumber (String | null): Phone number of the authenticated user.
  • wallets (Object[]): The multichain wallets of the authenticated user.

#Example

Typescript
01const { Magic, WalletType } = require('@magic-sdk/admin');
02const mAdmin = new Magic('SECRET_API_KEY');
03
04...
05
06// Get a token however you wish! Perhaps this is attached
07// to `req.authorization`
08const didToken = // ...
09
10// Gets user metadata based on the given DID Token
11const metadata = await mAdmin.users.getMetadataByTokenAndWallet(didToken, WalletType.ANY);

#Utils Module

The Utils Module and it's members are accessible on the Magic Admin SDK instance by the utils property.

Typescript
01const { Magic } = require('@magic-sdk/admin');
02
03const mAdmin = new Magic();
04
05mAdmin.utils;
06mAdmin.utils.parseAuthorizationHeader;

#parseAuthorizationHeader

#Arguments

parseAuthorizationHeader(header)

  • header (String): A request authorization header passed in from the client-side application that looks like Bearer WyIweG...n0iXQ==.

#Returns

string: The DID token embedded in the authorization header.

This is only available to Admin SDK version 1.1.0 and above.

Example

Typescript
01const { Magic } = require('@magic-sdk/admin');
02const mAdmin = new Magic();
03
04...
05
06/* Gets the DID token from a login request */
07app.get('/login', async (req: any, res: any) => {
08  /*
09    Assumes DIDToken was passed in the Authorization header
10    in the standard `Bearer {token}` format.
11   */
12  const didToken = mAdmin.utils.parseAuthorizationHeader(req.headers.authorization);
13  /* You can now do stuff with the DID token */
14});

#Errors & Warnings

#SDKError

The SDKError class is exposed for instanceof operations.

Typescript
01import { SDKError } from '@magic-sdk/admin';
02
03try {
04  // Something async...
05catch (err) {
06  if (err instanceof SDKError) {
07    // Handle...
08  }
09}

Additionally, an enumeration of relevant error codes is also exposed for convenience and human readability:

Typescript
01import { ErrorCode } from '@magic-sdk/admin';
02
03ErrorCode.MissingApiKey;
04ErrorCode.MissingAuthHeader;
05ErrorCode.IncorrectSignerAddress;
06// and so forth...
07// Please reference the `Enum Key` column of the error table below.

#Error Codes

Enum KeyDescription
TokenExpiredThe supplied DID Token is invalid due to an expired timestamp.
TokenCannotBeUsedYetThe nbf ("not before") field of the supplied DID Token is set in the future. By default, a 5 minute leeway is added to the timestamp.
IncorrectSignerAddressThe supplied DID Token is invalid due to a mismatch between the signature origin and the claimed user public address.
FailedRecoveryProofThe supplied DID Token could not be recovered using Elliptic Curve recovery.
ApiKeyMissingThe API key required for a particular action is missing or malformed.
MalformedTokenErrorThe supplied DID Token could not be successfully parsed.
ServiceErrorAn error occurred while communicating with the Magic API. Be sure to check the data property of the error object for additional context.

#data & Nested Errors

For additional context about an error, the SDKError.data property contains an array of potentially illuminating metadata. At the moment, this property is reserved for service errors when communication to Magic APIs fail.

Did you find what you were looking for?