Skip to main content

Web SDK Integration Guide

The Shufti Web SDK is a lightweight JavaScript library that runs on your own web pages and captures the behavioural and device signals only a browser can observe, such as how a user types, moves and clicks, and whether their device or browser shows signs of automation or tampering. The Web SDK is integrated separately from the verification requests you send through the API.

Each customer action you want to protect, such as sign-up or a withdrawal, is recorded as one session. This guide covers the complete integration: issuing a session token from your server, loading the SDK, starting and ending a session for each action, linking the session to your customer, and sending the submitted form fields.

The integration has two parts:

  • Server side: your server requests a one-time session token from Shufti for each session. No other API call is required.
  • Client side: your pages load the Web SDK and start, update and end the session. The SDK sends the session data securely to Shufti over HTTPS and WebSocket.

For the server-side verification request, see the API Integration Guide.

info

To start using the Shufti Web SDK, please contact Shufti's support team at tech@shuftipro.com or your Shufti point of contact.

Before You Start​

You need the following before you integrate the Web SDK:

ItemWhere to find itUsed by
Client IDBack Office → Settings → API Configurations → API KeysYour server, to request a session token. Your pages don't need it: the token carries it.
Secret KeyThe same pageYour server only. Never put it in a web page or an app.
SDK bundle URLhttps://bbv.shuftipro.com/behavioural-biometric-js/bundle.jsYour pages. The same URL for trial and production.

Trial and Production Keys​

  • Separate keys: your trial and production accounts have different keys. The Production Account switch at the top of the Back Office selects which keys you see.
  • Testing: use the trial keys while you test. Sessions started with a trial token are recorded under your trial account.
  • Going live: use the production keys on your live site.
  • Enabled keys: session tokens work only with keys Shufti has enabled. If you regenerate your Secret Key, or want to test with your trial keys, contact Shufti to enable them.

Get a Session Token​

Every session starts with a one-time session token. Your server gets it from Shufti with your Client ID and Secret Key, the same Basic Auth as the rest of the Shufti API, and gives it to the page, which passes it to initializeSDK(). Once Shufti turns on session tokens for your account, it accepts a session only with a valid token, so nobody can start sessions under your account from outside your site.

RequestValue
EndpointPOST https://bbv.shuftipro.com/get/access/token, the same for trial and production
AuthorizationBasic base64(<Client ID>:<Secret Key>)
BodyNone
Response{ "access_token": "…", "expires_in": 3600 }, with expires_in in seconds
get-session-token
curl -X POST https://bbv.shuftipro.com/get/access/token \
-u "$SHUFTI_CLIENT_ID:$SHUFTI_SECRET_KEY"
  • One token per session: each token works once and expires after one hour. Get a new one each time a page starts a session.
  • Server only: a call made from a browser is refused. Make it from your server and pass only the token to the page.
  • Visitors not signed in: the sign-up session starts before the customer has an account, so your own token endpoint must also work for visitors who are not signed in yet.
HTTP statusMeaning
200The token was issued.
401Wrong Client ID or Secret Key, or the account is not yet set up for session tokens. Check your keys, or contact Shufti.
403The call came from a browser. Make it from your server.
500Shufti could not issue the token. Try again.

Load the SDK​

Load the SDK directly from https://bbv.shuftipro.com/behavioural-biometric-js/bundle.js, and only on pages where an action is recorded. Don't host your own copy of the file: Shufti updates it at that link with fixes.

The snippets in the next sections explain the pieces. The file to copy into your app is the complete webSdk.js in End a Session and Move to the Next Action.

webSdk.js
// webSdk.js: one place in your app that owns the Web SDK
const WEB_SDK_URL = "https://bbv.shuftipro.com/behavioural-biometric-js/bundle.js";
let sdkPromise = null;

export function loadWebSdk() {
if (!sdkPromise) {
sdkPromise = import(/* webpackIgnore: true */ /* @vite-ignore */ WEB_SDK_URL)
.catch((err) => {
sdkPromise = null; // allow a retry on the next action
console.warn("Web SDK not loaded", err);
return null; // never block the customer's journey
});
}
return sdkPromise; // resolves to the SDK module, or null
}

If the Web SDK fails to load, the customer carries on as normal. Never wait on the Web SDK before letting the customer submit a form.

Content Security Policy​

If your site sends a Content Security Policy header, allow:

DirectiveAdd
script-srchttps://bbv.shuftipro.com
connect-srchttps://bbv.shuftipro.com wss://bbv.shuftipro.com

Start a Session​

Call initializeSDK() once when the action's page or step opens, with the options below. It resolves to true once the SDK has started; Shufti accepts or refuses the session a moment later (see When the Web SDK Does Not Start). The SDK creates the session reference itself; read it with getReference().

The block below shows the call. Use the startSdkSession in the complete webSdk.js in your app, because it also closes the previous action's session.

start-a-session
import { loadWebSdk } from "./webSdk.js";

export async function startSdkSession({ actionType, customerId = null, token }) {
const sdk = await loadWebSdk();
if (!sdk) return null;

const started = await sdk.initializeSDK({
token, // one-time session token from your server
action_type: actionType, // the action being recorded, e.g. "signup"
customer_id: customerId, // your customer_unique_id; null at sign-up
maskText: true, // required: no typed text leaves the page
recordRepeatClicks: true,
detectPrivateBrowsing: true,
collectDeviceSignals: true,
detectDeveloperTools: false,
collectMotionSensors: false,
});
if (!started) {
console.warn("Web SDK not started:", sdk.getLastError()); // e.g. token_invalid
return null;
}
return sdk.getReference(); // the session reference the SDK created
}

Initialization Options​

OptionValueNotes
tokenFrom your serverRequired. The one-time session token (see Get a Session Token). A new one for every session.
action_typeThe action typeThe action this session records, for example signup (see One Session per Action).
customer_idYour customer IDYour stable internal customer ID, the same value you send to Shufti KYC as customer_unique_id: a string of up to 255 characters, not an email address or phone number. Use it for the same customer in every session. null at sign-up.
refA UUIDOptional. Only for an action that spans several pages (see Multi-page flows). Otherwise leave it out and the SDK creates the reference.
maskTexttrueRequired. Without it the SDK sends what the customer types. The contents of password fields, and of one-time code fields marked autocomplete="one-time-code", are never sent either way; only the timing of key presses in them.
recordRepeatClickstrueKeeps rapid clicks on the same spot, a sign of automation.
detectPrivateBrowsingtrueDetects private or incognito browsing.
collectDeviceSignalstrueDevice and browser checks: cookie ID, graphics and spoofing checks, keyboard layout, screen values. Sets a first-party cookie, bbv_cid, for 400 days; list it in your cookie notice.
detectDeveloperToolsfalseOptional, off by default. A periodic check for open browser developer tools.
collectMotionSensorsfalseOptional, off by default. Motion readings and browser permission states and, where Shufti's configuration for your account asks for them, device orientation and location. The browser may ask the customer for location permission.

Every option is off unless you pass true, so pass the values shown above.

When the Web SDK Does Not Start​

initializeSDK() resolves to false when the SDK cannot start, and getLastError() returns why. The SDK prints nothing to the console in production, so your code has to read it.

ReasonMeaningFix
token_invalidThe token is unknown or already used by another sessionGet a new token for every session
token_expiredThe token is older than one hourGet the token when the page starts the session, not earlier
client_inactiveYour account is switched off for the Web SDKContact Shufti
filters_unavailableYour account is not set up for the Web SDKContact Shufti
network_errorShufti could not be reachedCheck your Content Security Policy and the network
origin_not_allowedThis page's domain is not on your account's allowed listSend Shufti the domains where you load the SDK
init_failedAnything else went wrong while startingTry again on the next action; contact Shufti if it persists
Any other valueShufti refused the session for another reasonContact Shufti with the value

Refused after start. Shufti checks the token again when it receives the session, a few seconds after initializeSDK() resolved to true. If the token was used in the meantime, for example by another tab, getLastError() returns token_invalid or token_expired. The complete webSdk.js reads it again eight seconds after the start for that reason.

One Session per Action​

Each action is its own session. action_type names the action: lowercase letters, digits and underscores, starting with a letter, at most 64 characters. An action_type that does not match the format is ignored, with no error.

The actions below are examples. Use the names of your own actions.

Actionaction_typeStart the session whenEnd the session when
SignupsignupThe sign-up form (email, password) opensThe account is created; send the email and call setCustomerId() first
RegistrationregistrationThe registration or profile form (name, date of birth, address, phone) opensThe customer completes it, including any phone code step; call setFields() first
First purchasefirst_purchaseThe checkout opens for the customer's first purchase or depositThe purchase is submitted
WithdrawalwithdrawalThe withdrawal or payout form opens, on every withdrawalThe withdrawal request is submitted
  • Leaving without completing. When the tab closes or the page unloads, the pagehide listener in the complete webSdk.js ends the session. In a single-page app there is no unload between actions, so startSdkSession for the next action ends the previous session first. If the customer leaves an action's route without starting another, call endSdkSession("pagehide") from your router.
  • Multi-page flows. Each full page load starts its own session, with its own token. When one action spans several pages, pass the same ref (any UUID you create and store for the flow) to initializeSDK() on every page of that action: those sessions then share one reference. Send the fields and end the session on the last page.
  • Same customer ID from sign-up on. Shufti links a customer's sessions by customer_id: set with setCustomerId() at sign-up, and passed on every later session.

The sign-up session starts before the account exists, so it has no customer_id. Send the email the customer submits with setFields(). Once the account is created, call setCustomerId(customerId) and then end the session. This links the sign-up session to the customer.

sign-up
import { startSdkSession, sendSdkFields, setSdkCustomer, endSdkSession } from "./webSdk.js";

// when the sign-up form opens: there is no customer ID yet
startSdkSession({ actionType: "signup" }); // not awaited: the form shows at once

form.addEventListener("submit", async (event) => {
event.preventDefault();
const v = formValues();
sendSdkFields({ // on every attempt; the last one counts
email: v.email,
password_hash: await sha256Hex(v.password), // optional, see Password Hash below
});
const account = await submitSignup(v); // your own code
if (account) {
setSdkCustomer(account.customerId); // your customer_unique_id
endSdkSession();
} // failed attempts keep the session open
});

formValues(), submitSignup(), submitRegistration(), submitCode(), codeValue() and customer.id in the samples stand for your own code.

Form Fields​

Shufti receives the form fields in two ways, and uses both:

  • Marked inputs. Add data-bbv-field to each input. The SDK reads that field's final value when the customer leaves the field and when the form is submitted. With maskText: true, unmarked inputs stay masked.
  • setFields(). Pass the values your form submits, just before you submit them. These are the values Shufti uses. Call it again on a retry; the last values sent before the session ends count.
marked-inputs
<input  name="firstName"  data-bbv-field="first_name">
<input name="lastName" data-bbv-field="last_name">
<input name="dob" data-bbv-field="dob" type="date">
<input name="street" data-bbv-field="address_line">
<input name="city" data-bbv-field="city">
<select name="state" data-bbv-field="state">...</select>
<input name="zip" data-bbv-field="postal_code">
<select name="country" data-bbv-field="country">...</select>
<input name="phone" data-bbv-field="phone" type="tel">

Form Field Keys​

Field keyFieldFormat
emailEmail addressAs entered
usernameUsernameAs entered, if your sign-up has one
first_nameFirst nameAs entered
last_nameLast nameAs entered
full_nameFull nameAs entered; only for pages that cannot split the name
dobDate of birthYYYY-MM-DD
address_lineStreet addressAs entered
cityCityAs entered
stateState or regionAs entered; for US states the two-letter code, for example NJ
postal_codePostal or ZIP codeAs entered
countryCountryTwo-letter ISO 3166-1 code, for example US
phonePhone numberE.164, for example +15551234567
password_hashA hash of the passwordHexadecimal, 32 to 128 characters, for example SHA-256. Only through setFields(), never from a marked input. See Password Hash.
note

Only these keys are accepted; any other key is dropped before it leaves the page. Values are trimmed and cut to 256 characters. Never mark a password field: the SDK ignores password inputs even if they are marked.

registration
import { startSdkSession, sendSdkFields, endSdkSession } from "./webSdk.js";

// when the registration form opens: the customer already has an account
startSdkSession({ actionType: "registration", customerId: customer.id });

form.addEventListener("submit", async (event) => {
event.preventDefault();
const v = formValues();
sendSdkFields({ // exactly what you submit to your server
first_name: v.firstName,
last_name: v.lastName,
dob: v.dob, // YYYY-MM-DD
address_line: v.street,
city: v.city,
state: v.state, // for US states the two-letter code, for example "NJ"
postal_code: v.zip,
country: v.country, // two-letter ISO code, for example "US"
phone: v.phone, // E.164, for example "+15551234567"
});
const ok = await submitRegistration(v); // your own code
if (!ok) return; // failed attempts keep the session open
});

// A phone code step belongs to the same session: end it once the code is verified.
codeForm.addEventListener("submit", async (event) => {
event.preventDefault();
const verified = await submitCode(codeValue()); // your own code
if (verified) endSdkSession();
});

Password Hash​

The password itself is never sent. To let Shufti spot accounts that share a password, your page can send a hash of it as password_hash, made in the page before the form is submitted. Shufti encrypts it with its own key before storing it.

  • Optional: leave it out if you don't want password matching.
  • Same function for every customer: use one hash function, without a per-customer salt, so that the same password always gives the same hash. A value that is not hexadecimal of 32 to 128 characters is dropped.
password-hash
// SHA-256 of the password, as lowercase hexadecimal
async function sha256Hex(text) {
const bytes = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest("SHA-256", bytes);
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
}

End a Session and Move to the Next Action​

End the session when the action completes. Shut the SDK down only when the next action starts or the customer leaves your app, and always end the session first: the helpers below do both in the right order.

This is the complete webSdk.js: copy this file. It covers single-page and multi-page sites, contains the final form of the functions shown above, and every helper waits for the session to start, so call them in any order without awaiting them.

webSdk.js
// webSdk.js: the one place in your app that talks to the Web SDK
const WEB_SDK_URL = "https://bbv.shuftipro.com/behavioural-biometric-js/bundle.js";
let sdkPromise = null;
let current = null; // promise of { sdk, ref, ended } for the current action

export function loadWebSdk() {
if (!sdkPromise) {
sdkPromise = import(/* webpackIgnore: true */ /* @vite-ignore */ WEB_SDK_URL)
.catch((err) => {
sdkPromise = null; // allow a retry on the next action
console.warn("Web SDK not loaded", err);
return null; // never block the customer's journey
});
}
return sdkPromise;
}

// One-time session token for this session, from YOUR server, which calls Shufti with
// the Client ID and Secret Key. Replace the URL with your own endpoint.
async function getSessionToken() {
const res = await fetch("/your-api/web-sdk-token", { method: "POST", credentials: "include" });
if (!res.ok) throw new Error(`session token: ${res.status}`);
return (await res.json()).access_token;
}

// Call when the action's page or step opens. Not awaited where the customer waits.
// ref is optional: pass the same value on every page of one multi-page action.
export function startSdkSession({ actionType, customerId = null, ref = undefined }) {
const previous = current;
current = (async () => {
const [sdk, token] = await Promise.all([
loadWebSdk(),
getSessionToken().catch((err) => {
console.warn("Web SDK session token not received", err);
return null; // the action goes unrecorded; the customer carries on
}),
]);
if (!sdk || !token) return null;
const last = await previous;
if (last) { // close the previous action first
if (!last.ended) sdk.endSession("pagehide"); // the customer left it without completing
sdk.shutdownSDK();
}
const started = await sdk.initializeSDK({
token, action_type: actionType, customer_id: customerId, ref,
maskText: true, recordRepeatClicks: true, detectPrivateBrowsing: true,
collectDeviceSignals: true, detectDeveloperTools: false, collectMotionSensors: false,
});
if (!started) {
console.warn("Web SDK not started:", sdk.getLastError());
return null;
}
// Shufti accepts or refuses the session a few seconds after the start
setTimeout(() => {
const reason = sdk.getLastError();
if (reason) console.warn("Web SDK session refused:", reason);
}, 8000);
return { sdk, ref: sdk.getReference(), ended: false };
})().catch(() => null);
return current.then((session) => session && session.ref);
}

// The helpers below wait for the start, so they are safe to call
// right after startSdkSession.
async function withSession(call) {
const session = await current;
if (session) call(session);
}

// Sign-up: once the account exists, before ending the session.
export const setSdkCustomer = (customerId) =>
withSession((s) => s.sdk.setCustomerId(customerId));

// The values your form submits, before ending the session.
export const sendSdkFields = (fields) =>
withSession((s) => s.sdk.setFields(fields));

// Call when the action completes (successful submit). The SDK sends the end
// as soon as it can, even when the session has only just started.
export const endSdkSession = (reason = "final_status") =>
withSession((s) => {
if (s.ended) return; // a completed action is ended once
if (reason === "final_status") s.ended = true;
s.sdk.endSession(reason);
});

// Call on logout or when the customer leaves the area you record.
export async function stopWebSdk() {
const session = await current;
current = null;
if (!session) return;
if (!session.ended) session.sdk.endSession("pagehide");
session.sdk.shutdownSDK();
}

// A tab closed or a full page navigation also ends the session.
if (typeof window !== "undefined") {
window.addEventListener("pagehide", () => endSdkSession("pagehide"));
}
note

Do not await the Web SDK anywhere the customer waits. If startSdkSession returns null, the customer carries on and the action is simply not recorded.

Session Reference​

The SDK creates a new reference for every session. getReference() returns it, and startSdkSession above passes it back to your page. Storing it next to your own event is optional; it lets you match the session later.

Quick Reference​

The calls this integration uses. Anything else in the bundle is not part of it.

CallReturnsUse
POST /get/access/token{ access_token, expires_in }Your server only: one session token per session
initializeSDK(options)Promise<boolean>Start a session with its token (see Initialization Options)
getReference()string or nullThe session's reference; null before the first session has started
setCustomerId(customerId)booleanSign-up: link the session to the new customer before it ends
setFields(fields)booleanThe submitted field values (see Form Field Keys)
endSession(reason)booleanEnd the session; sent as soon as the session has started
getLastError()string or nullWhy the SDK did not start or Shufti refused the session
shutdownSDK()booleanStop recording, before the next action or on logout. Call endSession() first: shutdown alone does not end the session

reason is "final_status" when the action completes and "pagehide" when the page closes.

API Integration Guide​

The Web SDK does not replace your verification requests. Your server keeps sending verification requests through the API:

  • Fraud Signals: once a verification has finished, request its fraud score and signals with POST /fraud-signals. The parameters, signals and response are described in Fraud Signals.
  • Device metadata: for offsite verification requests, send the end user's IP address, user agent and device identifier in device_metadata (see General Parameters).

A sample offsite verification request with device metadata:

api-request-sample

//POST / HTTP/1.1
//Host: api.shuftipro.com
//Content-Type: application/json
//Authorization: Basic <base64 of Client ID:Secret Key>

{
"reference": "ABCD1234",
"email": "john.doe@example.com",
"document": {
"proof": "<base64 ID document image>",
"supported_types": ["id_card"]
},
"device_metadata": {
"ip_address": "203.0.113.24",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"device_fingerprint": "d9e8f7g6h5i4j3k2l1m0"
}
}

A sample Fraud Signals request for that verification:

fraud-signals-request-sample

//POST /fraud-signals HTTP/1.1
//Host: api.shuftipro.com
//Content-Type: application/json
//Authorization: Basic <base64 of Client ID:Secret Key>

{
"reference": "ABCD1234"
}