Verilive JavaScript SDK is a library that allows you to integrate liveness verification into your web application. It provides a simple API to start and manage liveness verification.
Integration Steps
Create a session in your backend by making a
POSTrequest to/liveness2/sessionendpoint.cURL example:
#!/usr/bin/env bash API_URL="<API_URL>" API_KEY="<your-api-key>" API_SECRET="<your-api-secret>" FLOW_ID="<your-flow-id>" PERSON_ID="<your-person-id>" ### THE LINES BELOW DOES NOT REQUIRE ANY MODIFICATIONS ### API_PATH="/liveness2/session" TIMESTAMP=$(date +%s) SIGNABLE_STR=$(echo -n -e "$TIMESTAMP$API_PATH") HMAC_DIGEST=$(echo -n $SIGNABLE_STR | openssl sha256 -hmac "$API_SECRET" | cut -d' ' -f2) DATA_JSON=$(cat <<-EOF { "person_id": "$PERSON_ID", "flow_id": "$FLOW_ID" } EOF ) curl -i -X POST "https://$API_URL$API_PATH" \ -H "Content-Type: application/json" \ -H "X-Verigram-Api-Version: 2.0" \ -H "X-Verigram-Api-Key: $API_KEY" \ -H "X-Verigram-Hmac-SHA256: $HMAC_DIGEST" \ -H "X-Verigram-Ts: $TIMESTAMP" \ -d "$DATA_JSON"The endpoint returns a JSON object containing
session_id,access_token,person_id, andflow_id. Pass these values directly to your frontend.In your web application, create a
Veriliveinstance:import { Verilive2, VeriliveError } from 'verilive-sdk'; const verilive = new Verilive2();Call the
start()method on the Verilive instance using the parameters obtained from your backend. The SDK mounts directly into thenodeelement you provide (a sized container in your layout) — see Embedded mode.import { Verilive2, VeriliveAlreadyStartedError, VeriliveCancelledByUserError, VeriliveUnmountedError, VeriliveContainerNotInDomError, VeriliveContainerInShadowDomError, VeriliveRootElementNotFoundError, VeriliveServerError, VeriliveNetworkError, VeriliveInternalError, VeriliveError, } from 'verilive-sdk'; const verilive = new Verilive2(); const node = document.getElementById('liveness-container'); if (!node) throw new Error('The container for mounting Verilive was not found'); try { const result = await verilive.start({ baseUrl: '<API_URL>', flowId: 'your-flow-id', accessToken: 'your-access-token', personId: 'your-person-id', sessionId: 'your-session-id', node, }); // the result is always { completed: true }, there is no verdict in this object. // console.log('Flow finished', result.completed); // request the final verdict on the backend by flow_id. } catch (error) { if (error instanceof VeriliveAlreadyStartedError) { // console.error('Verification has already started'); } else if (error instanceof VeriliveCancelledByUserError) { // console.log('Verification was cancelled by the user'); } else if (error instanceof VeriliveUnmountedError) { // console.log('SDK has been unmounted'); } else if (error instanceof VeriliveContainerNotInDomError) { // console.error('Node is not attached to the document'); } else if (error instanceof VeriliveContainerInShadowDomError) { // console.error('Node is inside a Shadow DOM'); } else if (error instanceof VeriliveRootElementNotFoundError) { // console.error('SDK root element was not found'); } else if (error instanceof VeriliveServerError) { // console.error('Server error during verification'); } else if (error instanceof VeriliveNetworkError) { // console.error('Network error during verification'); } else if (error instanceof VeriliveInternalError) { // console.error('Internal SDK error:', error.message); } else if (error instanceof VeriliveError) { // console.error('SDK error:', error.code, error.message); } else { // console.error('Unexpected error:', error); } }Handle the result and errors
start()returns an object:{ completed: true }.The
completedfield indicates that the flow has finished, including cases where the face is not classified as live. It does not represent the liveness verdict.You must check the liveness verification result on your backend before allowing the user to proceed to the next step.
Never make this decision on the frontend.
The SDK does not return the verdict to the client because client-side results can be tampered with.
You can retrieve the final verdict on your backend from Verilive system using the following endpoint:
GET /flow/{flow_id}/result.curl -X GET https://<API_URL>/flow/{flow-id}/result \ -H 'Content-Type: application/json' \ -H 'X-Verigram-Api-Version: 2.0' \ -H 'X-Verigram-Api-Key: <your-test-api-key>'import requests api_url = "https://<API_URL>" flow_id = "<flow-id>" api_key = "<your-test-api-key>" response = requests.get( f"{api_url}/flow/{flow_id}/result", headers={ "Content-Type": "application/json", "X-Verigram-Api-Version": "2.0", "X-Verigram-Api-Key": api_key, }, timeout=30, ) response.raise_for_status() result = response.json() print(result)
API Reference
Verilive2 class
Constructor
Creates and returns a new Verilive2 object.
Syntax:
new Verilive2(options?)Parameters:
options (optional) — An object used to configure the SDK. The available properties are:
language?: 'ru' | 'kz' | 'en'— Override the browser locale with a specific language (default: browser locale).
Example:
const verilive = new Verilive2({
language: 'en'
});
start() method
Starts the liveness verification process. Returns a Promise that resolves with a Verilive2Result upon completion or rejects with a VeriliveError if a critical SDK error occurs.
Only one start() call can run at a time, globally across all Verilive2 instances. If start() is called while another session is in progress, the SDK rejects the call with a VeriliveAlreadyStartedError.
Syntax:
start(params: {
flowId: string;
accessToken: string;
personId: string;
sessionId: string;
baseUrl?: string;
attemptsLeft?: number;
showStartScreen?: boolean;
showResultScreen?: boolean;
language?: 'ru' | 'kz' | 'en';
node: HTMLElement;
onRetry?: (params: OnRetryParams) => Promise<RetryData>;
}): Promise<Verilive2Result>
Parameters:
params — An object containing session and UI configuration:
node: HTMLElement— Required. The DOM element the SDK mounts into directly. The host owns the element's sizing and placement; the SDK fills it 100%. The element must be attached to the current document and must not be inside a Shadow DOM. Ifnodeis missing,start()throws aVeriliveInternalError. See Embedded mode for details.flowId: string— Required. The unique identifier for the verification flow, obtained from your backend.accessToken: string— Required. Authentication token obtained from the backend to authorize the session.personId: string— Required. The unique identifier for the individual undergoing verification.sessionId: string— Required. A unique ID for the current attempt.Note: Do not rely on this ID for final results; use
flowIdas it remains constant across retries.baseUrl?: string— Optional. Override the default API URL. Required for on-premises deployments.attemptsLeft?: number— Optional. Number of retry attempts allowed. When set, after all attempts are exhausted thestart()promise resolves with{ success: false }and the correspondingerrorCode. When not set, retry is managed by theonRetrycallback or the server.showStartScreen?: boolean— Optional. Whether to display the instruction screen before starting (default:true).showResultScreen?: boolean— Optional. Whether to show success/failure feedback screens (default:true).language?: 'ru' | 'kz' | 'en'— Optional. Override the language set in the constructor for this session.onRetry?: (params: OnRetryParams) => Promise<RetryData>— Optional. Callback for consumer-managed retry. Called when the user clicks retry. Must return new session credentials. If not provided, the SDK handles retry internally.
Return value:
Promise<Verilive2Result>— Resolves with{ completed: true }.
Example:
const result = await verilive.start({
flowId: 'your-flow-id',
accessToken: 'your-access-token',
personId: 'your-person-id',
sessionId: 'your-session-id',
baseUrl: 'https://liveness.company.com/',
showStartScreen: false,
showResultScreen: false,
node: document.getElementById('liveness-container')!,
});
// console.log(result);
// { completed: true }unmount() method
Unmounts the SDK if it is currently running. This interrupts the active liveness process and cleans up all associated resources. If a start() call is still in progress, the associated Promise will be rejected with a VeriliveUnmountedError.
Syntax:
unmount(): void
Example:
setTimeout(() => {
verilive.unmount();
}, 1000);
try {
await verilive.start({ flowId, accessToken, personId, sessionId, node });
} catch (error) {
// error will be a VeriliveUnmountedError after 1 second
}Error Handling
If an error occurs within Verilive2.start(), a VeriliveError exception is thrown.
All known errors are represented by subclasses of VeriliveError. Each instance has the following properties:
name: string— the class name (e.g., VeriliveServerError). For an unknown error code, name is VeriliveError.code: string— the error code.message: string— the error message. If the SDK does not provide a custom message, the default message from the table is used.
Class, code | When it occurs |
|---|---|
|
|
| The user cancels verification by navigating back in the browser or pressing Escape. |
|
|
|
|
|
|
| The SDK root element cannot be found during mounting. |
| The backend returns an error during verification. |
| A network error prevents verification from completing. |
| An environment failure or an internal SDK error occurs. |
| An unknown completion code is received that does not correspond to any of the child-classes listed above. |
Container errors are thrown by start() when node is provided but is invalid. If node is omitted entirely, the SDK throws VeriliveInternalError, not VeriliveContainerNotInDomError.
Retry Handling
The SDK supports two retry modes:
SDK-managed retry (default)
When the liveness check fails and attemptsLeft > 0, the SDK automatically shows a retry screen and handles the retry internally via the server endpoint.
const result = await verilive.start({
flowId, accessToken, personId, sessionId, node,
attemptsLeft: 3,
});Consumer-managed retry
Provide an onRetry callback to handle retry logic yourself. The callback receives the current session info and must return new session credentials.
const result = await verilive.start({
flowId, accessToken, personId, sessionId, node,
onRetry: async ({ sessionId, errorCode, attemptsLeft }) => {
// Request new session credentials from your backend
const response = await fetch('/api/retry-session', {
method: 'POST',
body: JSON.stringify({ sessionId }),
});
const data = await response.json();
return {
sessionId: data.sessionId,
accessToken: data.accessToken,
attemptsLeft: data.attemptsLeft,
};
},
});Embedded mode
The SDK mounts its UI directly into a DOM element you provide via node — no iframe, no postMessage. This lets the verification UI live inside your own layout (a card, a panel, a route) instead of a full-screen modal.
node is required. The host owns the element's sizing and placement; the SDK fills it 100%.
Requirements for node
Must be an
HTMLElementinstance attached to the currentdocument. A detached element throwsCONTAINER_NOT_IN_DOM.Must not be inside a Shadow DOM. The SDK throws
CONTAINER_IN_SHADOW_DOMbecause session recording (used for incident replay) cannot see across shadow boundaries.You own its size. Give it an explicit height (or a flex/grid/absolute box). If the element resolves to ~0px height, the SDK falls back to a full-screen overlay so the camera view doesn't collapse.
Example
import { Verilive2, VeriliveError } from 'verilive-sdk';
const verilive = new Verilive2({ language: 'en' });
// Контейнер с заданным размером, в который смонтируется SDK.
const container = document.getElementById('liveness-container'); // например, 480×700
if (!container) throw new Error('Контейнер для liveness не найден');
const result = await verilive.start({
flowId,
accessToken,
personId,
sessionId,
node: container,
});
// console.log(result);
// { completed: true }In React, hold the container with a ref and pass ref.current as node:
const containerRef = useRef<HTMLDivElement | null>(null);
const start = async () => {
const node = containerRef.current;
if (!node) return;
await verilive.start({ flowId, accessToken, personId, sessionId, node });
};
// <div ref={containerRef} style={{ width: 480, height: 700 }} />Usage Examples
React Example
import { useRef } from 'react';
import { Verilive2, VeriliveError } from 'verilive-sdk';
const verilive = new Verilive2({ language: 'en' });
function App() {
const containerRef = useRef<HTMLDivElement | null>(null);
const startVerification = async () => {
const node = containerRef.current;
if (!node) return;
try {
const response = await fetch('/api/get-verification-credentials');
const { flowId, accessToken, personId, sessionId } = await response.json();
const result = await verilive.start({
flowId, accessToken, personId, sessionId, node,
});
// console.log(result);
// { completed: true }
} catch (error) {
if (error instanceof VeriliveError) {
console.error('SDK error:', error.code, error.message);
}
}
};
return (
<div>
<button onClick={startVerification}>Start Verification</button>
<button onClick={() => verilive.unmount()}>Stop</button>
{/* Сюда монтируется SDK. Размером элемента управляет хост. */}
<div ref={containerRef} style={{ width: 480, height: 700 }} />
</div>
);
}Vanilla JavaScript Example
import { Verilive2, VeriliveError } from 'verilive-sdk';
const verilive = new Verilive2({ language: 'en' });
async function startVerification() {
// Контейнер с заданным размером, в который смонтируется SDK.
const node = document.getElementById('liveness-container');
if (!node) return;
try {
const response = await fetch('/api/get-verification-credentials');
const { flowId, accessToken, personId, sessionId } = await response.json();
const result = await verilive.start({
flowId, accessToken, personId, sessionId, node,
});
// console.log(result);
// { completed: true }
} catch (error) {
if (error instanceof VeriliveError) {
console.error('SDK error:', error.code, error.message);
}
}
}
document.getElementById('startButton').addEventListener('click', startVerification);History Management
The SDK manages the browser history to provide a seamless user experience. Understanding this mechanism is essential for proper integration with your application's routing.
How It Works
When the start() method is invoked, the SDK pushes a new entry onto the browser's history stack. When the liveness process is completed, canceled, or manually interrupted, the SDK automatically restores the previous history state.
If the user presses the browser Back button during the verification process, the SDK intercepts the navigation, cancels the verification, and rejects the start() promise with a VeriliveCancelledByUserError.
State Transitions
Successful Verification Completion. The SDK ensures the history returns to a clean state after the callback is executed.
Manual Unmount. If
unmount()is called, the SDK manually rolls back the history stack to the state existing prior to initialization.Browser Back Button. Pressing "Back" triggers a natural
popstateevent which the SDK uses to clean up and reject the pending promise with aVeriliveCancelledByUserError.
TypeScript Support
The SDK includes TypeScript type definitions. Import types as needed:
import {
Verilive2,
VeriliveError,
VeriliveAlreadyStartedError,
VeriliveCancelledByUserError,
VeriliveUnmountedError,
VeriliveContainerNotInDomError,
VeriliveContainerInShadowDomError,
VeriliveRootElementNotFoundError,
VeriliveServerError,
VeriliveNetworkError,
VeriliveInternalError,
type VeriliveConfig,
type StartParams,
type Verilive2Result,
type OnRetryParams,
type RetryData,
} from 'verilive-sdk';
const config: VeriliveConfig = {
language: 'en',
};
const verilive = new Verilive2(config);
const params: StartParams = {
flowId,
accessToken,
personId,
sessionId,
node,
};
const result: Verilive2Result = await verilive.start(params);
// result.completed === true