Enchanted Link via Client SDKs

This guide is meant for developers that are NOT using Descope Flows to design login screens and authentication methods.

If you'd like to use Descope Flows, Quick Start should be your starting point.

An enchanted link is a single-use link sent to the user for authentication (sign-up or sign-in) that validates their identity. The Descope service sends enchanted links via email.

Enchanted links are an enhanced version of magic links. Enchanted links enable users to start the login process on one device (the originating device) while clicking the enchanted link on a different device. When the user clicks the correct link, their session on the originating device is validated, and they are logged in. A special security feature of enchanted link is that the end-user needs to pick the correct link from the three links delivered to them.

The enchanted link flow within Descope for client SDK

TriangleAlert

Alert

Enchanted links are user friendly since the user does not have to switch tabs or applications to log in. The browser tab they initiated login from is the only tab they need to use.

Use Cases

  1. New user signup: The following actions must be completed, first User Sign-Up, then within the same route begin Polling for a valid session, and when the enchanted link is clicked User Verification
  2. Existing user signin: The following actions must be completed, first User Sign-In, then within the same route begin Polling for a valid session, and when the enchanted link is clicked User Verification
  3. Sign-Up or Sign-In (Signs up a new user or signs in an existing user): The following actions must be completed, first User Sign-Up or Sign-In, then within the same route begin Polling for a valid session, and when the enchanted link is clicked User Verification

Client SDK

For information on how to install and initialize the Descope Client SDK, please refer to the Client SDK Installation Guide.

User Sign-up

For registering a new user, your application client should accept user information, including a mandatory email used for verification. The application client should send this information to your application server. In this sample code, the enchanted link will be sent by email to email@company.com. The signup call returns a pendingRef and a linkId. Display the linkId to end user from your application so that they can click on the correct link in the email that they receive. Then your application will utilize the pendingRef to poll for verification status on the originating device.

Also note that signup is not complete without the user verification step below.

// Args:
//    user: user meta data for signup.
const user = {"name": "Joe Person", "phone": "+15555555555", "email": "email@company.com"}
//    loginId: email - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
const uri = "http://auth.company.com/api/verify_enchantedlink"
//    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }

const descopeSdk = useDescope();
const resp = await descopeSdk.enchantedLink.signUp(loginId, uri, user, signUpOptions);
if (!resp.ok) {
  console.log("Failed to initialize signup flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully initialized signup flow")
  const linkId = resp.data.linkId;
  console.log("linkId " + linkId)
  const pendingRef = resp.data.pendingRef;
  console.log("pendingRef " + pendingRef)
}
// Args:
//    user: user meta data for signup.
const user = {"name": "Joe Person", "phone": "+15555555555", "email": "email@company.com"}
//    loginId: email - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
const uri = "http://auth.company.com/api/verify_enchantedlink"
//    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeSdk.enchantedLink.signUp(loginId, uri, user, signUpOptions);
if (!resp.ok) {
  console.log("Failed to initialize signup flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully initialized signup flow")
  const linkId = resp.data.linkId;
  console.log("linkId " + linkId)
  const pendingRef = resp.data.pendingRef;
  console.log("pendingRef " + pendingRef)
}
<script>
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });

  async function enchantedLinkSignUp() {
    // Args:
    //    user: Optional user object to populate new user information.
    const user = {
      "name": document.getElementById("name").value,
      "phone": document.getElementById("phone").value,
      "email": document.getElementById("email").value
    }
    //    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
    const loginId = document.getElementById("email").value
    //    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
    const uri = "http://auth.company.com/api/verify_enchantedlink"
    //    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
    const signUpOptions = {
          "customClaims": {"claim": "Value1"},
          "templateOptions": {"option": "Value1"}
        }

    const resp = await descopeSdk.enchantedLink.signUp(loginId, uri, user, signUpOptions);
    if (!resp.ok) {
      window.alert("Failed to initialize signup flow\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully initialized signup flow")
      window.location.replace("./polling_enchantedlink?userId=" + encodeURIComponent(loginId) + "&pendingRef=" + encodeURIComponent(resp.data.pendingRef) + "&linkId=" + encodeURIComponent(resp.data.linkId))
    }
  }
</script>

User Sign-in

For authenticating a user, your application client should accept the user's identity (typically an email address or phone number). In this sample code, the enchanted link will be sent by email to email@company.com. The signin call returns a pendingRef and a linkId. Display the linkId to end user from your application so that they can click on the correct link in the email that they receive. Then your application will utilize the pendingRef to poll for verification status on the originating device.

Also note that signin is not complete without the user verification step below.

// Args:
//    loginId: email - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
const uri = "http://auth.company.com/api/verify_enchantedlink"
//    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
const loginOptions = {
      "stepup": false,
      "mfa": false,
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }
//    refreshToken (optional): the user's current refresh token in the event of stepup/mfa

const descopeSdk = useDescope();
const resp = await descopeSdk.enchantedLink.signIn(loginId, uri, loginOptions);
if (!resp.ok) {
  console.log("Failed to initialize signin flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully initialized signin flow")
  const linkId = resp.data.linkId;
  console.log("linkId " + linkId)
  const pendingRef = resp.data.pendingRef;
  console.log("pendingRef " + pendingRef)
}
// Args:
//    loginId: email - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
//    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
const uri = "http://auth.company.com/api/verify_enchantedlink"
//    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
const loginOptions = {
      "stepup": false,
      "mfa": false,
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }
//    refreshToken (optional): the user's current refresh token in the event of stepup/mfa

const resp = await descopeSdk.enchantedLink.signIn(loginId, uri, loginOptions);
if (!resp.ok) {
  console.log("Failed to initialize signin flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully initialized signin flow")
  const linkId = resp.data.linkId;
  console.log("linkId " + linkId)
  const pendingRef = resp.data.pendingRef;
  console.log("pendingRef " + pendingRef)
}
<script>
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });

  async function enchantedLinkSignIn() {
    // Args:
    //    loginId: email or phone for the user
    const loginId = document.getElementById("loginId").value
    //    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
    const uri = "http://auth.company.com/api/verify_enchantedlink"
    //    loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
    const loginOptions = {
          "stepup": false,
          "mfa": false,
          "customClaims": {"claim": "Value1"},
          "templateOptions": {"option": "Value1"}
        }
    //    refreshToken (optional): the user's current refresh token in the event of stepup/mfa

    const resp = await descopeSdk.enchantedLink.signIn(loginId, uri, loginOptions);
    if (!resp.ok) {
      window.alert("Failed to initialize signin flow\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully initialized signin flow")
      window.location.replace("./polling_enchantedlink?userId=" + encodeURIComponent(loginId) + "&pendingRef=" + encodeURIComponent(resp.data.pendingRef) + "&linkId=" + encodeURIComponent(resp.data.linkId))
    }
  }
</script>

User Sign-Up or Sign-In

For signing up a new user or signing in an existing user, you can utilize the signUpOrIn functionality. In this sample code, the enchanted link will be sent by email to email@company.com. The signin call returns a pendingRef and a linkId. Display the linkId to end user from your application so that they can click on the correct link in the email that they receive. Then your application will utilize the pendingRef to poll for verification status on the originating device.

Note that signUpOrIn is not complete without the user verification step below.

// Args:
//    loginId: email - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
//    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }

const descopeSdk = useDescope();
const resp = await descopeSdk.enchantedLink.signUpOrIn(loginId, uri, signUpOptions);
if (!resp.ok) {
  console.log("Failed to initialize signUpOrIn flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully initialized signUpOrIn flow")
  const linkId = resp.data.linkId;
  console.log("linkId " + linkId)
  const pendingRef = resp.data.pendingRef;
  console.log("pendingRef " + pendingRef)
}
// Args:
//    loginId: email - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
//    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
      "customClaims": {"claim": "Value1"},
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeSdk.enchantedLink.signUpOrIn(loginId, uri, signUpOptions);
if (!resp.ok) {
  console.log("Failed to initialize signUpOrIn flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully initialized signUpOrIn flow")
  const linkId = resp.data.linkId;
  console.log("linkId " + linkId)
  const pendingRef = resp.data.pendingRef;
  console.log("pendingRef " + pendingRef)
}
<script>
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });

  async function enchantedLinkSignUpOrIn() {
    // Args:
    //    loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
    const loginId = document.getElementById("email").value
    //    uri: (Optional) this is the link that user is sent (code appended) for verification. Your application needs to host this page and extract the token for verification. The token arrives as a query parameter named 't'
    const uri = "http://auth.company.com/api/verify_enchantedlink"
    //    signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
    const signUpOptions = {
          "customClaims": {"claim": "Value1"},
          "templateOptions": {"option": "Value1"}
        }

    const resp = await descopeSdk.enchantedLink.signUpOrIn(loginId, uri, signUpOptions);
    if (!resp.ok) {
      window.alert("Failed to initialize signup or in flow\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully initialized signup or in flow")
      window.location.replace("./polling_enchantedlink?userId=" + encodeURIComponent(loginId) + "&pendingRef=" + encodeURIComponent(resp.data.pendingRef) + "&linkId=" + encodeURIComponent(resp.data.linkId))
    }
  }
</script>

User Verification

Call the verify function from your verify url. This means that this function needs to be called when the user clicks the enchanted link. If the token is valid, the user will be authenticated and session returned to the polling thread (see next step).

// Args:
// token:  URL parameter containing the enchanted link token for example, https://auth.company.com/api/verify_enchantedlink?t=token.
const token = "xxxx"

const descopeSdk = useDescope();
const resp = await descopeSdk.enchantedLink.verify(token);
if (!resp.ok) {
  console.log("Failed to verify enchanted link")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully verified enchanted link")
}
// Args:
// token:  URL parameter containing the enchanted link token for example, https://auth.company.com/api/verify_enchantedlink?t=token.
const token = "xxxx"

const resp = await descopeSdk.enchantedLink.verify(token);
if (!resp.ok) {
  console.log("Failed to verify enchanted link")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully verified enchanted link")
}
<script>
  enchantedLinkVerify(tokenFromURL)

  async function enchantedLinkVerify(thisToken) {
    // Args:
    //  token:  URL parameter containing the enchanted link token for example, http://auth.company.com/api/verify_enchantedlink?t=token.
    const token = thisToken

    const resp = await descopeSdk.enchantedLink.verify(token);
    if (!resp.ok) {
      window.alert("Failed to verify Enchanted Link Token\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully verified OTP Enchanted Link Token")
      window.alert("Successfully completed Enchanted Link verification. This tab will close after you acknowledge this alert. Please return to your original window.")
      window.close();
    }
  }
</script>

Polling for valid session

On the route where you initialized the signIn, signUp, or signUpOrIn, you need to repeatedly poll for a valid session. get_session(token) is called repeatedly until the user clicks the enchanted link URL they received, so that the session on the initiating device can be directed to your desired page.

// Args:
//    pendingRef: Reference token received from signup or signin call.
const pendingRef = "xxxxx"

const descopeSdk = useDescope();
const resp = await descopeSdk.enchantedLink.waitForSession(pendingRef);
if (!resp.ok) {
  console.log("Failed to complete polling flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully completed polling flow")
  console.log(resp)
}
// Args:
//    pendingRef: Reference token received from signup or signin call.
const pendingRef = "xxxxx"

const resp = await descopeSdk.enchantedLink.waitForSession(pendingRef);
if (!resp.ok) {
  console.log("Failed to complete polling flow")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully completed polling flow")
  console.log(resp)
}
<script>
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });

  enchantedLinkVerify(pendingRef, userId)

  async function enchantedLinkVerify(thisPendingRef, myUserId) {
    // Args:
    //  token:  URL parameter containing the enchanted link token for example, http://auth.company.com/api/verify_enchantedlink?t=token.
    const pendingRef = thisPendingRef

    const resp = await descopeSdk.enchantedLink.waitForSession(pendingRef);
    if (!resp.ok) {
      window.alert("Failed to verify Enchanted Link Token\nStatus Code: " + resp.code
        + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
      console.log("Successfully verified OTP enchanted Link Token")
      window.location.replace("../loggedIn?userId=" + encodeURIComponent(myUserId) + "&sessionJwt=" + resp.data.sessionJwt)
    }
  }
</script>

Update Email

This function allows you to update the user's email address via email. This requires a valid refresh token. Once the user has received the enchanted link Code, you will need to host a page to verify the enchanted link code using the enchanted link Verify Function.

// Args:
//   loginId (str): The loginId of the user being updated
const loginId = "email@company.com"
//   email (str): The new email address. If an email address already exists for this end user, it will be overwritten
const email = "newEmail@company.com"
//   refreshToken (str): The session's refresh token (used for verification)
const refreshToken = "xxxxx"
//    updateOptions (UpdateOptions): this allows you to configure behavior during the authentication process.
const updateOptions = {
      "addToLoginIDs": true,
      "onMergeUseExisting": true,
      "templateOptions": {"option": "Value1"}
    }

const descopeSdk = useDescope();
const resp = await descopeSdk.enchantedLink.update.email(loginId, email, refreshToken, updateOptions);
if (!resp.ok) {
  console.log("Failed to start enchanted link email update")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully started enchanted link email update")
  console.log(resp.data)
}
// Args:
//   loginId (str): The loginId of the user being updated
const loginId = "email@company.com"
//   email (str): The new email address. If an email address already exists for this end user, it will be overwritten
const email = "newEmail@company.com"
//   refreshToken (str): The session's refresh token (used for verification)
const refreshToken = "xxxxx"
//    updateOptions (UpdateOptions): this allows you to configure behavior during the authentication process.
const updateOptions = {
      "addToLoginIDs": true,
      "onMergeUseExisting": true,
      "templateOptions": {"option": "Value1"}
    }

const resp = await descopeSdk.enchantedLink.update.email(loginId, email, refreshToken, updateOptions);
if (!resp.ok) {
  console.log("Failed to start enchanted link email update")
  console.log("Status Code: " + resp.code)
  console.log("Error Code: " + resp.error.errorCode)
  console.log("Error Description: " + resp.error.errorDescription)
  console.log("Error Message: " + resp.error.errorMessage)
}
else {
  console.log("Successfully started enchanted link email update")
  console.log(resp.data)
}
<script>
  let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });


  async function enchantedLinkUpdateEmail() {
    // Args:
    //   loginId (str): The loginId of the user being updated
    const loginId = "email@company.com"
    //   email (str): The new email address. If an email address already exists for this end user, it will be overwritten
    const email = "newEmail@company.com"
    //   refreshToken (str): The session's refresh token (used for verification)
    const refreshToken = "xxxxx"
    //    updateOptions (UpdateOptions): this allows you to configure behavior during the authentication process.
    const updateOptions = {
          "addToLoginIDs": true,
          "onMergeUseExisting": true,
          "templateOptions": {"option": "Value1"}
        }

    const resp = await descopeSdk.enchantedLink.update.email(loginId, email, refreshToken, updateOptions);
    if (!resp.ok) {
        window.alert("Failed to start enchanted link email update\nStatus Code: " + resp.code
            + "\nError Code: " + resp.error.errorCode + "\nError Description: " + resp.error.errorDescription + "\nError Message: " + resp.error.errorMessage)
    }
    else {
        console.log("Successfully started enchanted link email update")
        console.log(resp.data.sessionJwt)
        window.alert("Successfully initialized Enchanted Link Flow, please close this window and go to your email or phone and click the link to log in.")
    }
  }
</script>

Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?
Was this helpful?

On this page