Skip to main content

Web JavaScript

Initial Setup

The LoginID Web SDK provides a set of functions and components that can be integrated into your web (browser) application. To use it, you'll need to configure the SDK with your LoginID credentials and then call the appropriate methods for signup and signin functionalities.

This SDK facilitates a smooth integration process, eliminating the need to redirect users to external pages outside of your application.

Required settings:

  • Base URL

Create an Application

Create a new application to obtain your base URL.

Add SDK to Existing Application

npm install --save @loginid/websdk3

Create an SDK Instance

NPM
import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);
info

You can view the source code here.

Class LoginIDWebSDK

Extends LoginIDBase to support creation and authentication of passkeys.

Defined in packages/websdk3/src/loginid/index.ts:10

constructor

new LoginIDWebSDK(config: LoginIDConfig): LoginIDWebSDK

ParameterTypeRequiredDescription
configLoginIDConfigYesConfiguration for LoginID FIDO service.
config.appId?stringNoThe optional app ID for specific application.
config.baseUrlstringYesThe base URL for LoginID FIDO service which can be obtained on the dashboard.
config.disableAnalytics?booleanNoIf true, disables sending analytics/events to LoginID. Defaults to false.

LoginIDWebSDK

Defined in packages/websdk3/src/loginid/index.ts:13

authenticateWithPasskey

This method authenticates a user with a passkey and may trigger additional browser dialogs to guide the user through the process.

A short-lived authorization token is returned, allowing access to protected resources for the given user such as listing, renaming or deleting passkeys.

authenticateWithPasskey(
    username?: string,
    options?: AuthenticateWithPasskeysOptions,
): Promise<AuthResult>

ParameterTypeRequiredDescription
usernamestring = ""YesUsername to authenticate. When empty, usernameless passkey authentication is performed.
optionsAuthenticateWithPasskeysOptions = {}YesAdditional authentication options.
options.abortController?AbortControllerNoThis should be used with the options.autoFill option to trigger the cancellation of the passkey conditional UI. Pass this if additional passkeys API calls may be anticipated on the current context page.
options.authzToken?stringNoAuthorization token used for accessing protected resources typically used for adding multiple passkeys to a user.
options.autoFill?booleanNoWhen true it will enable passkeys on the browser autofill suggestions if supported (conditional UI). Username does not need to be set.
options.callbacks?CallbacksNoCallback functions that can be triggered on various events during the authentication process.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<AuthResult>

interface AuthResult {
    deviceId?: string;
    fallbackOptions?: FallbackOptions;
    isAuthenticated: boolean;
    isFallback: boolean;
    passkeyId?: string;
    token: string;
    userId: string;
}

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

// Button click handler
async function handleSignupButtonClick() {
const username = "billy@loginid.io";

try {
// Sign in with a passkey
const signinResult = await lid.authenticateWithPasskey(username);
// Handle the signin result
console.log("Signin Result:", signinResult);
} catch (error) {
// Handle errors
console.error("Error during signin:", error);
}
}

// Attach the click handler to a button
const signinButton = document.getElementById("signinButton");
signinButton.addEventListener("click", handleSigninButtonClick);

Defined in packages/websdk3/src/loginid/controllers/passkeys.ts:220

authenticateWithPasskeyAutofill

Authenticates a user by utilizing the browser's passkey autofill capabilities.

A short-lived authorization token is returned, allowing access to protected resources for the given user such as listing, renaming or deleting passkeys.

authenticateWithPasskeyAutofill(
    options?: AuthenticateWithPasskeyAutofillOptions,
): Promise<AuthResult>

ParameterTypeRequiredDescription
optionsAuthenticateWithPasskeyAutofillOptions = {}YesAdditional authentication options.
options.abortController?AbortControllerNoThis should be used with the options.autoFill option to trigger the cancellation of the passkey conditional UI. Pass this if additional passkeys API calls may be anticipated on the current context page.
options.authzToken?stringNoAuthorization token used for accessing protected resources typically used for adding multiple passkeys to a user.
options.autoFill?booleanNoWhen true it will enable passkeys on the browser autofill suggestions if supported (conditional UI). Username does not need to be set.
options.callbacks?CallbacksNoCallback functions that can be triggered on various events during the authentication process.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<AuthResult>

interface AuthResult {
    deviceId?: string;
    fallbackOptions?: FallbackOptions;
    isAuthenticated: boolean;
    isFallback: boolean;
    passkeyId?: string;
    token: string;
    userId: string;
}

import { isConditionalUIAvailable, LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

window.addEventListener("load", async (event) => {
try {
const result = await isConditionalUIAvailable();
if (!result) {
// If conditional UI is not supported then continue without it or handle what to do
// next here.
return;
}

const result = await lid.authenticateWithPasskeyAutofill();
console.log("Authentication Result:", result);
} catch (error) {
// Handle errors
console.error("Error during authentication:", error);
}
});

Defined in packages/websdk3/src/loginid/controllers/passkeys.ts:338

confirmTransaction

This method initiates a non-repudiation signature process by generating a transaction-specific challenge and then expects the client to provide an assertion response using a passkey.

This method is useful for confirming actions such as payments or changes to sensitive account information, ensuring that the transaction is being authorized by the rightful owner of the passkey.

For a more detailed guide click here.

confirmTransaction(
    username: string,
    txPayload: string,
    options?: ConfirmTransactionOptions,
): Promise<TxComplete>

ParameterTypeRequiredDescription
usernamestringYesThe username of the user confirming the transaction.
txPayloadstringYesThe transaction-specific payload, which could include details such as the transaction amount, recipient, and other metadata necessary for the transaction.
optionsConfirmTransactionOptions = {}YesOptional parameters for transaction confirmation.
options.authzToken?stringNoAuthorization token used for accessing protected resources typically used for adding multiple passkeys to a user.
options.callbacks?CallbacksNoCallback functions that can be triggered on various events during the authentication process.
options.nonce?stringNoA unique nonce to ensure the transaction's integrity and prevent replay attacks
options.txType?stringNoSpecify the type of transaction being confirmed for additional validation.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<TxComplete>

TxComplete: { authCred?: Passkey; credentialId: string; token: string }

import { LoginIDWebSDK } from "@loginid/websdk3";

const config = {
baseUrl: BASE_URL,
};

const lid = new LoginIDWebSDK(config);

const username = "jane@securelogin.com";
const txPayload = JSON.stringify({
amount: 100,
recipient: "bob@securepay.com",
});
// Unique transaction nonce
const nonce = "f846bb01-492e-422b-944a-44b04adc441e";

async function handleTransactionConfirmation() {
try {
// Confirm the transaction
const confirmationResult = await lid.confirmTransaction(
username,
txPayload,
nonce
);
// Handle the transaction confirmation result
console.log("Transaction Confirmation Result:", confirmationResult);

// Check nonce
const { nonce: resultNonce } = confirmationResult;
if (nonce !== resultNonce) {
throw new Error("Nonce mismatch");
}
} catch (error) {
// Handle errors
console.error("Error during transaction confirmation:", error);
}
}

// Attach the click handler to a button for transaction confirmation
const confirmTransactionButton = document.getElementById(
"confirmTransactionButton"
);
confirmTransactionButton.addEventListener(
"click",
handleTransactionConfirmation
);

Defined in packages/websdk3/src/loginid/controllers/passkeys.ts:472

createPasskey

This method helps to create a passkey. The only required parameter is the username, but additional attributes can be provided in the options parameter. Note: While the authorization token is optional, it must always be used in a production environment. You can skip it during development by adjusting the app configuration in the LoginID dashboard.

A short-lived authorization token is returned, allowing access to protected resources for the given user such as listing, renaming or deleting passkeys.

createPasskey(
    username: string,
    authzToken?: string,
    options?: CreatePasskeyOptions,
): Promise<AuthResult>

ParameterTypeRequiredDescription
usernamestringYesUsername to register.
authzTokenstring = ""YesAuthorization token for passkey creation.
optionsCreatePasskeyOptions = {}YesAdditional passkey creation options.
options.authzToken?stringNoAuthorization token used for accessing protected resources typically used for adding multiple passkeys to a user.
options.callbacks?CallbacksNoCallback functions that can be triggered on various events during the authentication process.
options.crossPlatform?booleanNoIndicates that the credential should be a cross-platform FIDO credential (e.g., a hardware security key or a hybrid passkey).
options.displayName?stringNoA human-palatable name for the user account, intended only for display on your passkeys and modals.
options.passkeyName?stringNoA custom label or nickname for the passkey itself, used to help users distinguish between multiple passkeys. If not provided, a default name may be auto-generated based on the device and/or user-agent.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<AuthResult>

interface AuthResult {
    deviceId?: string;
    fallbackOptions?: FallbackOptions;
    isAuthenticated: boolean;
    isFallback: boolean;
    passkeyId?: string;
    token: string;
    userId: string;
}

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

// Button click handler
async function handleSignupButtonClick() {
const username = "billy@loginid.io";

try {
// Sign up with a passkey
const signupResult = await lid.createPasskey(username);
// Handle the signup result
console.log("Signup Result:", signupResult);
} catch (error) {
// Handle errors
console.error("Error during signup:", error);
}
}

// Attach the click handler to a button
const signinButton = document.getElementById("signinButton");
signinButton.addEventListener("click", handleSigninButtonClick);

Defined in packages/websdk3/src/loginid/controllers/passkeys.ts:99

deletePasskey

Delete a specified passkey by ID from LoginID. The user must be fully authorized for this call to succeed.

deletePasskey(id: string, options?: DeletePasskeyOptions): Promise<void>

ParameterTypeRequiredDescription
idstringYesThe ID of the passkey to delete.
optionsDeletePasskeyOptions = {}YesAdditional options for deleting the passkey.
options.authzToken?stringNoAuthorization token used for authorizing passkey management actions.

Promise<void>

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

const passkeyId = "abc123";

// Delete the passkey user credential
try {
// Signin with passkey
const signinResult = await lid.authenticateWithPasskey(username);

// Find a way to retrieve passkey ID
await lid.deletePasskey(passkeyId);
// Passkey credential successfully deleted
} catch (error) {
// Handle errors
console.error("Error deleting passkey:", error);
}

Defined in packages/websdk3/src/loginid/controllers/passkey-manager.ts:181

getSessionInfo

Check whether the user of the current browser session is authenticated and returns user info. This info is retrieved locally and no requests to backend are made.

getSessionInfo(): null | SessionInfo

null|SessionInfo

interface SessionInfo {
    id: string;
    rpId: string;
    username: string;
}

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);
const username = "billy@loginid.io";

try {
// Retrieve session information
await lid.authenticateWithPasskey(username);
const sessionInfo = lid.getSessionInfo();
console.log("Session Information:", sessionInfo);
} catch (error) {
console.error("Error retrieving session information:", error);
}

Defined in packages/core/dist/controllers/index.d.ts:89

listPasskeys

This method returns list of passkeys associated with the current user. The user must be fully authorized for this call to succeed.

listPasskeys(options?: ListPasskeysOptions): Promise<PasskeyCollection>

ParameterTypeRequiredDescription
optionsListPasskeysOptions = {}YesAdditional options for listing passkeys.
options.authzToken?stringNoAuthorization token used for authorizing passkey management actions.

Promise<PasskeyCollection>

PasskeyCollection: Passkey[]

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

// Button click handler for signing in
async function handleSigninButtonClick() {
const username = "billy@loginid.io";

try {
// Sign in with a passkey
await lid.authenticateWithPasskey(username);

// List all user credentials
const passkeys = await lid.listPasskeys();
// Handle the sign-in result
} catch (error) {
// Handle errors
console.error("Error during obtaining passkeys:", error);
}
}

// Attach the click handler to a button
const signinButton = document.getElementById("signinButton");
signinButton.addEventListener("click", handleSigninButtonClick);

Defined in packages/websdk3/src/loginid/controllers/passkey-manager.ts:73

logout

Clears current user session. This method is executed locally and it just deletes authorization token from local Cookies.

logout(): void

void

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

try {
// Retrieve user information
await lid.authenticateWithPasskey(username);
lid.logout();
const info = lid.getSessionInfo();
// false
console.log("Is user signed in?", info !== null);
} catch (error) {
console.error("Error:", error);
}

Defined in packages/core/dist/controllers/index.d.ts:121

renamePasskey

Renames a specified passkey by ID. The user must be fully authorized for this call to succeed.

renamePasskey(
    id: string,
    name: string,
    options?: RenamePasskeyOptions,
): Promise<void>

ParameterTypeRequiredDescription
idstringYesThe ID of the passkey to rename.
namestringYesThe new name for the passkey.
optionsRenamePasskeyOptions = {}YesAdditional options for renaming the passkey.
options.authzToken?stringNoAuthorization token used for authorizing passkey management actions.

Promise<void>

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

const passkeyId = "abc123";
const newCredName = "New Passkey Credential Name";

// Rename the passkey user credential
try {
// Signin with passkey
await lid.authenticateWithPasskey(username);

// Find a way to retrieve passkey ID
await lid.renamePasskey(passkeyId, newCredName);
// Passkey credential successfully renamed
} catch (error) {
// Handle errors
console.error("Error during passkey credential renaming:", error);
}

Defined in packages/websdk3/src/loginid/controllers/passkey-manager.ts:126

requestAndSendOtp

This method requests an OTP from the backend to be sent via the selected method. The method of delivery should be based on the user's choice from the list of available options. This can be found in the result of authenticateWithPasskey method as fallbackOptions.

requestAndSendOtp(
    username: string,
    method?: Message,
    options?: RequestAndSendOtpOptions,
): Promise<void>

ParameterTypeRequiredDescription
usernamestringYesUsername to request and send the OTP to.
methodMessage = "email"YesMethod to send the code, either 'email' or 'sms'. Default is 'email'.
optionsRequestAndSendOtpOptions = {}YesAdditional options for sending the OTP.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<void>

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

const username = "billy@loginid.io";

async function sendUserOTPHandler() {
try {
// Send OTP to a user via email
await lid.requestAndSendOtp(username, "email");
console.log("OTP sent successfully.");
} catch (error) {
console.error("Error sending code:", error);
}
}

const sendOtpButton = document.getElementById("button");
sendOtpButton.addEventListener("click", sendUserOTPHandler);

Defined in packages/websdk3/src/loginid/controllers/otp.ts:147

requestOtp

This method returns a one-time OTP to be displayed on the current device. The user must be authenticated on this device. The OTP is meant for cross-authentication, where the user reads the OTP from the screen and enters it on the target device.

requestOtp(username: string, options?: RequestOtpOptions): Promise<Otp>

ParameterTypeRequiredDescription
usernamestringYesThe username used for passkey authentication and OTP request.
optionsRequestOtpOptions = {}YesAdditional request OTP options.
options.abortController?AbortControllerNoThis should be used with the options.autoFill option to trigger the cancellation of the passkey conditional UI. Pass this if additional passkeys API calls may be anticipated on the current context page.
options.authzToken?stringNoAuthorization token used for accessing protected resources typically used for adding multiple passkeys to a user.
options.autoFill?booleanNoWhen true it will enable passkeys on the browser autofill suggestions if supported (conditional UI). Username does not need to be set.
options.callbacks?CallbacksNoCallback functions that can be triggered on various events during the authentication process.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<Otp>

interface Otp {
    code: string;
    expiresAt: string;
}

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

// Button click handler
async function handleRequestOTPButtonClick() {
const username = "billy@loginid.io";

try {
// Request OTP with passkey
const result = await lid.requestOtp(username);
const otp = result.code;
console.log("The OTP is: ", otp);
} catch (error) {
// Handle errors
console.error("Error during authentication:", error);
}
}

// Attach the click handler to a button
const requestOTPButton = document.getElementById("requestOTPButton");
requestOTPButton.addEventListener("click", handleRequestOTPButtonClick);

Defined in packages/websdk3/src/loginid/controllers/passkeys.ts:387

validateOtp

This method verifies the OTP and returns an authorization token, which can be used with the passkeyCreate() method to create a new passkey. The authorization token has a short validity period and should be used immediately.

validateOtp(
    username: string,
    otp: string,
    options?: ValidateOtpOptions,
): Promise<AuthResult>

ParameterTypeRequiredDescription
usernamestringYesUsername to validate with.
otpstringYesOTP to validate.
optionsValidateOtpOptions = {}YesAdditional authentication options.
options.usernameType?"phone"
"other"
NoThe type of username validation to be used. Defaults to other.

Promise<AuthResult>

interface AuthResult {
    deviceId?: string;
    fallbackOptions?: FallbackOptions;
    isAuthenticated: boolean;
    isFallback: boolean;
    passkeyId?: string;
    token: string;
    userId: string;
}

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

// Use the SDK components for signup and signin
const lid = new LoginIDWebSDK(config);

// Button click handler to generate a code with passkey
async function handleRequestOTPButtonClick() {
const username = "billy@loginid.io";

try {
// Request OTP with passkey
const result = await lid.requestOtp(username);
// Extract the OTP from the response
const otp = result.code;

// Authenticate with the OTP
// You can authenticate on another device with this OTP
const authenticateResult = await lid.validateOtp(username, otp);
// Handle the authentication result
console.log("Authentication Result:", authenticateResult);
} catch (error) {
// Handle errors
console.error("Error during authentication:", error);
}
}

// Attach the click handler to a button
const requestOtpButton = document.getElementById("requestOtpButton");
requestOtpButton.addEventListener("click", handleRequestOTPButtonClick);

Defined in packages/websdk3/src/loginid/controllers/otp.ts:79

verifyConfigSettings

Validates the application's configuration settings and provides a suggested correction if any issues are detected.

verifyConfigSettings(): Promise<VerifyConfigResult>

Promise<VerifyConfigResult>

interface VerifyConfigResult {
    code?: string;
    isValid: boolean;
    message?: string;
    solution?: string;
}

import { LoginIDWebSDK } from "@loginid/websdk3";

// Obtain credentials from LoginID
const BASE_URL = process.env.BASE_URL;

// Initialize the SDK with your configuration
const config = {
baseUrl: BASE_URL,
};

const lid = new LoginIDWebSDK(config);

async function checkConfig() {
const result = await lid.verifyConfigSettings();

if (result.isValid) {
console.log('Configuration is valid');
} else {
console.error(`Error: ${result.message} (Code: ${result.code})`);
console.info(`Solution: ${result.solution}`);
}
}

checkConfig();

// Attach the click handler to a button
const checkConfigButton = document.getElementById("button");
checkConfigButton.addEventListener("click", checkConfig);

Defined in packages/core/dist/controllers/index.d.ts:57