OTP Authentication with 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.
A one-time password (OTP) is an automatically generated string sent to the user during the onboarding (sign-up or sign-in) process to authenticate that user. The OTP can be sent to an email address or a mobile phone as a voice call or SMS (text message). A typical method for implementing OTP has two sets of functionality you need to program: user interaction and session verification.
Use Cases
- New user signup: The following actions must be completed, first User Sign-Up then User Verification
- Existing user signin: The following actions must be completed, first User Sign-In then User Verification
- 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 User Verification
Client SDK
Install SDK
npm i --save @descope/react-sdknpm i --save @descope/nextjs-sdknpm i --save @descope/web-js-sdknpm i --save @descope/vue-sdknpm i --save @descope/angular-sdkImport and initialize SDK
For more information about the baseUrl, baseStaticUrl, and baseCdnUrl parameters, refer to the Base URL Configuration section.
Parameters:
baseUrl: Custom domain that must be configured to manage token response in cookies. This makes sure every request to our service is through your custom domain, preventing accidental domain blockages.baseStaticUrl: Custom domain to override the base URL that is used to fetch static files.baseCdnUrl: Custom domain to override the base URL used to load external script assets (e.g., SDKs or widgets) dynamically at runtime.persistTokens: Controls whether session tokens are stored in browser localStorage. Enabled by default and accessible viagetToken(). Set tofalseto avoid client-side storage of tokens to reduce XSS risk.autoRefresh: Controls whether the session is automatically refreshed when the token is expired. Enabled by default. Set tofalseto disable automatic refresh of the session.sessionTokenViaCookie: Controls whether the session token is stored in a cookie instead of localStorage. IfpersistTokensis true, then by default, the token is stored in localStorage. Set this totrueto store the token in a JS cookie instead.storeLastAuthenticatedUser: Determines if the last authenticated user's info is saved in localStorage. Enabled by default and accessible viagetUser(). Set tofalseto disable this behavior.keepLastAuthenticatedUserAfterLogout: Controls whether user info is kept after logout. Disabled by default. Set totrueto store user data on logout.
import { AuthProvider } from '@descope/react-sdk'
import { Descope, useDescope } from '@descope/react-sdk'
const AppRoot = () => {
return (
<AuthProvider
projectId="__ProjectID__"
baseUrl="https://auth.app.example.com"
baseCdnUrl="https://assets.app.example.com" // specify a custom CDN URL for fetching external scripts and resources
persistTokens={true} // set to `false` to disable token storage in browser to prevent XSS
autoRefresh={true} // set to `false` to disable automatic refresh of the session
sessionTokenViaCookie={false} // set to `true` to store the session token in a JS cookie instead of localStorage
storeLastAuthenticatedUser={true} // set to `false` to disable storing last user
keepLastAuthenticatedUserAfterLogout={false} // set to `true` to persist user info after logout
>
<App />
</AuthProvider>
);
};import { AuthProvider } from '@descope/nextjs-sdk';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<AuthProvider
projectId="__ProjectID__"
baseUrl="<URL>"
baseCdnUrl="https://assets.app.example.com" // specify a custom CDN URL for fetching external scripts and resources
persistTokens={true} // set to `false` to disable token storage in browser to prevent XSS
autoRefresh={true} // set to `false` to disable automatic refresh of the session
sessionTokenViaCookie={false} // set to `true` to store the session token in a JS cookie instead of localStorage
storeLastAuthenticatedUser={true} // set to `false` to disable storing last user
keepLastAuthenticatedUserAfterLogout={false} // set to `true` to persist user info after logout
>
<html lang="en">
<body>{children}</body>
</html>
</AuthProvider>
);
}import DescopeSdk from '@descope/web-js-sdk';
try {
const descopeSdk = DescopeSdk({
projectId: '__ProjectID__',
baseUrl: 'https://auth.app.example.com',
baseCdnUrl="https://assets.app.example.com", // specify a custom CDN URL for fetching external scripts and resources
persistTokens: true, // set to `false` to disable token storage in browser to prevent XSS
autoRefresh: true, // set to `false` to disable automatic refresh of the session
sessionTokenViaCookie: false, // set to `true` to store the session token in a JS cookie instead of localStorage
storeLastAuthenticatedUser: true, // set to `false` to disable storing last user
keepLastAuthenticatedUserAfterLogout: false, // set to `true` to persist user info after logout
});
} catch (error) {
// handle the error
console.log("failed to initialize: " + error)
}import { createApp } from "vue";
import App from "@/App.vue";
import descope, { getSdk } from "@descope/vue-sdk";
const app = createApp(App);
app.use(router);
app.use(descope, {
projectId: '__ProjectID__',
baseUrl: "<base url>",
baseCdnUrl: "https://assets.app.example.com", // specify a custom CDN URL for fetching external scripts and resources
persistTokens: true, // set to `false` to disable token storage in browser to prevent XSS
autoRefresh: true, // set to `false` to disable automatic refresh of the session
sessionTokenViaCookie: false, // set to `true` to store the session token in a JS cookie instead of localStorage
storeLastAuthenticatedUser: true, // set to `false` to disable storing last user
keepLastAuthenticatedUserAfterLogout: false, // set to `true` to persist user info after logout
});
const sdk = getSdk();
sdk?.onSessionTokenChange((newSession) => {
// here you can implement custom logic when the session is changing
});// app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DescopeAuthModule, DescopeAuthService, descopeInterceptor } from '@descope/angular-sdk';
import { AppComponent } from './app.component';
import {
HttpClientModule,
provideHttpClient,
withInterceptors
} from '@angular/common/http';
import { zip } from 'rxjs';
export function initializeApp(authService: DescopeAuthService) {
return () => zip([authService.refreshSession(), authService.refreshUser()]);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
DescopeAuthModule.forRoot({
projectId: 'YOUR_PROJECT_ID',
baseUrl: '<URL>',
baseCdnUrl: "https://assets.app.example.com", // specify a custom CDN URL for fetching external scripts and resources
persistTokens: true, // set to `false` to disable token storage in browser to prevent XSS
autoRefresh: true, // set to `false` to disable automatic refresh of the session
sessionTokenViaCookie: false, // set to `true` to store the session token in a JS cookie instead of localStorage
storeLastAuthenticatedUser: true, // set to `false` to disable storing last user
keepLastAuthenticatedUserAfterLogout: false // set to `true` to persist user info after logout
})
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [DescopeAuthService],
multi: true
},
provideHttpClient(withInterceptors([descopeInterceptor]))
],
bootstrap: [AppComponent]
})
export class AppModule { }OIDC Configuration
If you're using our SDK as an OIDC client with our Federated Apps, you can initialize the oidcConfig parameter with the following items:
applicationId: This is the application id, that can be found within the settings of your Federated ApplicationredirectUri: This is the url that will be redirected to if the user is unauthenticated. The default redirect URI will be used if not provided.scope: This is a string of the scopes that the OIDC client will request from Descope. This should be one string value with spaces in between each scope. The default scopes are:'openid email roles descope.custom_claims offline_access'
User Sign-Up
For registering a new user, your application client should accept user information, including an email or
phone number used for verification. In this sample code, the OTP verification will be sent by email
to email@company.com. To change the delivery method to send the OTP verification as a Text Message (SMS), you would
change the deliveryMethod to sms within the below example.
Note
Note that signup is not complete without the user verification step below.
// Args:
// user: Optional user object to populate new user information.
const user = { "name": "Joe Person", "phone": "+15555555555", "email": "email@company.com"}
// loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
// 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.otp.signUp[deliveryMethod](loginId, 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")
}// Args:
// user: Optional user object to populate new user information.
const user = { "name": "Joe Person", "phone": "+15555555555", "email": "email@company.com"}
// loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
// signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
"customClaims": {"claim": "Value1"},
"templateOptions": {"option": "Value1"}
}
const resp = await descopeSdk.otp.signUp[deliveryMethod](loginId, 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")
}<script>
let descopeSdk = Descope({projectId: '__ProjectID__'"});
async function otpSignUp(method) {
// 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
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = method
// signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
"customClaims": {"claim": "Value1"},
"templateOptions": {"option": "Value1"}
}
const resp = await descopeSdk.otp.signUp[deliveryMethod](loginId, 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("./otpVerify?userId=" + encodeURIComponent(loginId) + "&deliveryMethod=" + deliveryMethod)
}
}
</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 OTP verification will be sent by email to email@company.com.
Note
Note that signin is not complete without the user verification step below.
// Args:
// loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
// 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.otp.signIn[deliveryMethod](loginId, 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")
}// Args:
// loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
// 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.otp.signIn[deliveryMethod](loginId, 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")
}<script>
let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
async function otpSignIn(method) {
// Args:
// loginId: email or phone for the user
const loginId = document.getElementById("loginId").value
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = method
// 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.otp.signIn[deliveryMethod](loginId, 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("./otpVerify?userId=" + encodeURIComponent(loginId) + "&deliveryMethod=" + deliveryMethod)
}
}
</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.
Only user loginId is necessary for this function. In this sample code, the OTP verification will be
sent by email to email@company.com. To change the delivery method to send the OTP verification as a Text Message (SMS), you would
change the deliveryMethod to sms within the below example.
Note
Note that signUpOrIn is not complete without the user verification step below.
// Args:
// loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
// 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.otp.signUpOrIn[deliveryMethod](loginId, 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")
}// Args:
// loginId: email or phone - becomes the loginId for the user from here on and also used for delivery
const loginId = "email@company.com"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
// signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
"customClaims": {"claim": "Value1"},
"templateOptions": {"option": "Value1"}
}
const resp = await descopeSdk.otp.signUpOrIn[deliveryMethod](loginId, 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")
}<script>
let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
async function otpSignUpOrIn(method) {
// 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
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = method
// signUpOptions (SignUpOptions): this allows you to configure behavior during the authentication process.
const signUpOptions = {
"customClaims": {"claim": "Value1"},
"templateOptions": {"option": "Value1"}
}
const resp = await descopeSdk.otp.signUpOrIn[deliveryMethod](loginId, 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("./otpVerify?userId=" + encodeURIComponent(loginId) + "&deliveryMethod=" + deliveryMethod)
}
}
</script>User Verification
The next step in authenticating the user is to verify the code entered by the user, using OTP verify code
function. The function will return all the necessary JWT tokens,
claims and user information. You can use the JWT tokens for session validation in your application middleware or app
server for every route needs an authenticated user.
// Args:
// loginId (str): The loginId of the user being validated
const loginId = "email@company.com"
// code (str): The authorization code enter by the end user during signup/signin
const code = "xxxxxx"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
const descopeSdk = useDescope();
const resp = await descopeSdk.otp.verify[deliveryMethod](loginId, code);
if (!resp.ok) {
console.log("Failed to verify OTP code")
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 OTP ")
console.log(resp.data)
}// Args:
// loginId (str): The loginId of the user being validated
const loginId = "email@company.com"
// code (str): The authorization code enter by the end user during signup/signin
const code = "xxxxxx"
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = "email"
const resp = await descopeSdk.otp.verify[deliveryMethod](loginId, code);
if (!resp.ok) {
console.log("Failed to verify OTP code")
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 OTP ")
console.log(resp.data)
}<script>
let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
async function otpVerify() {
// Args:
// loginId (str): The loginId of the user being validated
const loginId = userId
// code (str): The authorization code enter by the end user during signup/signin
const code = document.getElementById("otpCode").value
// deliveryMethod: Delivery method to use to send OTP. Supported values include "email", "voice, or "sms"
const deliveryMethod = method
const resp = await descopeSdk.otp.verify[deliveryMethod](loginId, code);
if (!resp.ok) {
window.alert("Failed to verify OTP code\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 ")
console.log(resp.data.sessionJwt)
window.location.replace("../loggedIn?userId=" + encodeURIComponent(loginId) + "&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 OTP Code, you will need to host a page to verify the OTP code using the OTP 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.otp.update.email(loginId, email, refreshToken, updateOptions);
if (!resp.ok) {
console.log("Failed to start OTP 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 OTP 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.otp.update.email(loginId, email, refreshToken, updateOptions);
if (!resp.ok) {
console.log("Failed to start OTP 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 OTP email update")
console.log(resp.data)
}<script>
let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
async function otpUpdateEmail() {
// 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.otp.update.email(loginId, email, refreshToken, updateOptions);
if (!resp.ok) {
window.alert("Failed to start OTP 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 OTP email update")
console.log(resp.data.sessionJwt)
window.location.replace("../otpVerify?userId=" + encodeURIComponent(loginId) + "&sessionJwt=" + resp.data.sessionJwt)
}
}
</script>Update Phone
This function allows you to update the user's phone number address via SMS. This requires a valid refresh token. Once the user has received the OTP Code, you will need to host a page to verify the OTP code using the OTP Verify Function.
// Args:
// deliveryMethod: Delivery method to use to send OTP.
const deliveryMethod = "sms"
// loginId (str): The loginId of the user being updated
const loginId = "phone@company.com"
// phone (str): The new phone number. If a phone number already exists for this end user, it will be overwritten
const phone = "+12223334455"
// 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 useDescope.otp.update.phone(deliveryMethod, loginId, phone, refreshToken, updateOptions);
if (!resp.ok) {
console.log("Failed to start OTP phone 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 OTP phone update")
console.log(resp.data)
}// Args:
// deliveryMethod: Delivery method to use to send OTP.
const deliveryMethod = "sms"
// loginId (str): The loginId of the user being updated
const loginId = "phone@company.com"
// phone (str): The new phone number. If a phone number already exists for this end user, it will be overwritten
const phone = "+12223334455"
// 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 useDescope.otp.update.phone(deliveryMethod, loginId, phone, refreshToken, updateOptions);
if (!resp.ok) {
console.log("Failed to start OTP phone 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 OTP phone update")
console.log(resp.data)
}<script>
let descopeSdk = Descope({projectId: '__ProjectID__', persistTokens: true, autoRefresh: true });
async function otpUpdateEmail() {
// Args:
// deliveryMethod: Delivery method to use to send OTP.
const deliveryMethod = "sms"
// loginId (str): The loginId of the user being updated
const loginId = "phone@company.com"
// phone (str): The new phone number. If a phone number already exists for this end user, it will be overwritten
const phone = "+12223334455"
// 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 useDescope.otp.update.phone(deliveryMethod, loginId, phone, refreshToken, updateOptions);
if (!resp.ok) {
window.alert("Failed to start OTP phone 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 OTP phone update")
console.log(resp.data.sessionJwt)
window.location.replace("../otpVerify?userId=" + encodeURIComponent(loginId) + "&sessionJwt=" + resp.data.sessionJwt)
}
}
</script>Session Validation
The final step of completing the authentication with Descope is to validate the user session. Descope provides rich session management capabilities, including configurable session timeouts and logout functions. You can find the details and sample code for client session validation here.
Checkpoint
Your application is now integrated with Descope. Please test with sign-up or sign-in use case.