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.
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:
| Item | Where to find it | Used by |
|---|---|---|
| Client ID | Back Office → Settings → API Configurations → API Keys | Your server, to request a session token. Your pages don't need it: the token carries it. |
| Secret Key | The same page | Your server only. Never put it in a web page or an app. |
| SDK bundle URL | https://bbv.shuftipro.com/behavioural-biometric-js/bundle.js | Your 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.
| Request | Value |
|---|---|
| Endpoint | POST https://bbv.shuftipro.com/get/access/token, the same for trial and production |
| Authorization | Basic base64(<Client ID>:<Secret Key>) |
| Body | None |
| Response | { "access_token": "…", "expires_in": 3600 }, with expires_in in seconds |
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 status | Meaning |
|---|---|
200 | The token was issued. |
401 | Wrong Client ID or Secret Key, or the account is not yet set up for session tokens. Check your keys, or contact Shufti. |
403 | The call came from a browser. Make it from your server. |
500 | Shufti 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: 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:
| Directive | Add |
|---|---|
script-src | https://bbv.shuftipro.com |
connect-src | https://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.
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
| Option | Value | Notes |
|---|---|---|
token | From your server | Required. The one-time session token (see Get a Session Token). A new one for every session. |
action_type | The action type | The action this session records, for example signup (see One Session per Action). |
customer_id | Your customer ID | Your 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. |
ref | A UUID | Optional. Only for an action that spans several pages (see Multi-page flows). Otherwise leave it out and the SDK creates the reference. |
maskText | true | Required. 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. |
recordRepeatClicks | true | Keeps rapid clicks on the same spot, a sign of automation. |
detectPrivateBrowsing | true | Detects private or incognito browsing. |
collectDeviceSignals | true | Device 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. |
detectDeveloperTools | false | Optional, off by default. A periodic check for open browser developer tools. |
collectMotionSensors | false | Optional, 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.
| Reason | Meaning | Fix |
|---|---|---|
token_invalid | The token is unknown or already used by another session | Get a new token for every session |
token_expired | The token is older than one hour | Get the token when the page starts the session, not earlier |
client_inactive | Your account is switched off for the Web SDK | Contact Shufti |
filters_unavailable | Your account is not set up for the Web SDK | Contact Shufti |
network_error | Shufti could not be reached | Check your Content Security Policy and the network |
origin_not_allowed | This page's domain is not on your account's allowed list | Send Shufti the domains where you load the SDK |
init_failed | Anything else went wrong while starting | Try again on the next action; contact Shufti if it persists |
| Any other value | Shufti refused the session for another reason | Contact 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.
| Action | action_type | Start the session when | End the session when |
|---|---|---|---|
| Signup | signup | The sign-up form (email, password) opens | The account is created; send the email and call setCustomerId() first |
| Registration | registration | The registration or profile form (name, date of birth, address, phone) opens | The customer completes it, including any phone code step; call setFields() first |
| First purchase | first_purchase | The checkout opens for the customer's first purchase or deposit | The purchase is submitted |
| Withdrawal | withdrawal | The withdrawal or payout form opens, on every withdrawal | The withdrawal request is submitted |
- Leaving without completing. When the tab closes or the page unloads, the
pagehidelistener in the completewebSdk.jsends the session. In a single-page app there is no unload between actions, sostartSdkSessionfor the next action ends the previous session first. If the customer leaves an action's route without starting another, callendSdkSession("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) toinitializeSDK()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 withsetCustomerId()at sign-up, and passed on every later session.
Link the Customer and Send Form Fields
Sign-up: Link the New Customer
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.
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-fieldto each input. The SDK reads that field's final value when the customer leaves the field and when the form is submitted. WithmaskText: 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.
<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 key | Field | Format |
|---|---|---|
email | Email address | As entered |
username | Username | As entered, if your sign-up has one |
first_name | First name | As entered |
last_name | Last name | As entered |
full_name | Full name | As entered; only for pages that cannot split the name |
dob | Date of birth | YYYY-MM-DD |
address_line | Street address | As entered |
city | City | As entered |
state | State or region | As entered; for US states the two-letter code, for example NJ |
postal_code | Postal or ZIP code | As entered |
country | Country | Two-letter ISO 3166-1 code, for example US |
phone | Phone number | E.164, for example +15551234567 |
password_hash | A hash of the password | Hexadecimal, 32 to 128 characters, for example SHA-256. Only through setFields(), never from a marked input. See Password Hash. |
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.
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.
// 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: 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"));
}
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.
| Call | Returns | Use |
|---|---|---|
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 null | The session's reference; null before the first session has started |
setCustomerId(customerId) | boolean | Sign-up: link the session to the new customer before it ends |
setFields(fields) | boolean | The submitted field values (see Form Field Keys) |
endSession(reason) | boolean | End the session; sent as soon as the session has started |
getLastError() | string or null | Why the SDK did not start or Shufti refused the session |
shutdownSDK() | boolean | Stop 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:
//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:
//POST /fraud-signals HTTP/1.1
//Host: api.shuftipro.com
//Content-Type: application/json
//Authorization: Basic <base64 of Client ID:Secret Key>
{
"reference": "ABCD1234"
}