Skip to navigation

Expo Integration

Learn how to integrate the HUMAN Expo SDK wrapper into an Expo app.

This guide is relevant for the current Mobile SDK. While we highly recommend using the latest version, if you are using a legacy integration, refer to the iOS or Android documentation.

You can integrate the SDK into an Expo project. This article explains how to integrate and implement the HUMAN Expo SDK wrapper into an Expo app.

Integrate the HUMAN Expo Module

To integrate the HUMAN SDK into your Expo app, follow these steps:

1

Install the package

In your project root, run:

npm install @humansecurity/expo-mobile-sdk
2

Add the plugin

Without this step, Android builds will fail to resolve the HUMAN SDK dependency.

The config plugin is available starting from version 1.0.8 and later. If you are using an earlier version (1.0.2 – 1.0.6), skip this step and continue to Step 3.

Add the plugin to your Expo configuration (app.json or app.config.js) so the Android dependency repository is automatically configured:

{
"expo": {
"plugins": [
"@humansecurity/expo-mobile-sdk"
]
}
}
3

Run prebuild

Generate the native project files:

npx expo prebuild

If your project does not use expo prebuild, you must manually add the HUMAN Maven repository so Android can resolve the SDK dependencies.

Add the following line everywhere you define repositories, such as in settings.gradle, build.gradle, or module-level Gradle files:

repositories {
// ... your existing repos
maven { url 'https://jfrog.humansecurity.com/artifactory/human-android-sdk/' }
}

The config plugin automatically adds this repository during npx expo prebuild. In custom or bare workflows, this must be added manually to ensure proper Android dependency resolution.

Start the SDK

When starting the SDK, start the SDK as soon as possible, and only once. Call startWithAppId in your Expo main entry point (index.tsx) or where you register and initialize one-time services. Start the SDK outside of any UI component to avoid lifecycle issues. If your app sends a URL request to your server before the SDK starts, the attached headers won’t include the latest updated tokens. As a result:

  • The Enforcer may block the request, and
  • The SDK will not be able to present a challenge to the user

Below is an example implementation:

Don’t forget to replace <APP_ID> with your actual Application ID.

import { HSPolicy, HumanSecurity } from "@humansecurity/expo-mobile-sdk";
// Initialize SDK once on app startup
(() => {
HumanSecurity.startWithAppId("<APP_ID>")
.then(() => {
console.log("SDK started successfully");
})
.catch((error) => {
console.error("Error starting the SDK:", error);
});
})();

In particular, note the following:

  1. Initialization: We start the SDK as early as possible and only once. You can move this code to a different function or file and export it as long as it’s only called once.
  2. Policy configuration: An optional HSPolicy class can configure the SDK’s behavior. This object defines settings such as hybridAppPolicy.webRootDomains. This class has two settings:
    • hybridAppPolicy: Use this if your app operates in hybrid mode, meaning it has a WebView that loads a site that’s also protected by HUMAN and running its sensor. Configure all relevant website domains with the application ID. Hybrid is supported for Expo WebView when webRootDomains is set. Set each domain to the bare registrable root (example.com). A leading dot is accepted and equivalent, and a leading www. is stripped to that root. Do not list a subdomain such as api.example.com. The Expo module turns supportExternalWebViews on. See WebView container support for more information.
    • detectionPolicy: This setting lets you configure whether the SDK can send touch and motion events, either touch only or both touch and motion, to the server to improve detection. By default, it’s off, and you can choose to enable it.
  3. Starting the SDK: We call startWithAppId with the following parameters:
    • Your Application ID. If you have multiple IDs, see our guide on how to handle them.
    • The policy object, if needed.

Integrate with Bot Defender

1

Send your requests through the SDK and check for a blocked request

  1. Your application adds the SDK’s HTTP headers to the URL request. Include them on every request, and do not cache them. They contain a token with an expiration date, and the SDK keeps that token up to date. Each request should call the HumanSecurity module so the headers are not reused from a previous call.
  2. Your application sends the URL request.
  3. If the response is blocked, pass the response body, status code, and URL to the SDK. Call canHandleResponse. If it returns true, call handleResponse to present the challenge. When using axios, you may need to call JSON.stringify(error.response?.data) on the response body before passing it and handle the blocked response in the catch block because axios treats it as a failed request.
  4. handleResponse resolves to HSBotDefenderChallengeResult:
    • SOLVED: The user successfully completed the challenge.
    • CANCELLED: The user dismissed or failed to complete the challenge.
    • FAILED: The SDK was unable to handle the response, usually indicating that something wasn’t passed correctly to handleResponse.
  5. You can await handleResponse, which waits until the user solves the challenge. You can also continue your flow and handle the result in the .then block.

Below are example implementations using the Fetch API or axios:

import HumanSecurity, { HSBotDefenderChallengeResult } from "@humansecurity/expo-mobile-sdk";
static async makeApiCall(url: string): Promise<void> {
try {
const headers = await HumanSecurity.BD.headersForURLRequest(HumanSecurityManager.appId);
const response = await fetch(url, {
method: "GET",
headers,
});
const statusCode = response.status;
if (statusCode !== 200) {
const responseText = await response.text();
const canHandle = HumanSecurity.BD.canHandleResponse(responseText, statusCode, url);
if (canHandle) {
HumanSecurity.BD.handleResponse(responseText, statusCode, url)
.then((result) => {
if (result === HSBotDefenderChallengeResult.SOLVED) {
console.log("Challenge solved successfully! Retrying request...");
} else {
console.log("Challenge was cancelled, or failed.");
}
})
.catch((error) => {
console.error("Error handling response:", error);
});
} else {
console.log("Response cannot be handled by the library.");
}
} else {
console.log(`API Call Successful with status ${statusCode}`);
}
} catch (error) {
console.error("Error making API call:", error);
}
}
2

Handle blocked requests

When the Enforcer blocks a request, it returns a JSON string in the response body with an HTTP status code of 403, which includes metadata for the SDK. For example:

{
"vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
"uuid": "fd01e6d6-9cf2-11ee-808c-acde48001122",
"page": "...",
"appId": "PXj9y4Q8Em",
"action": "captcha",
"collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
}

Your app should pass the entire JSON as response in a string format, along with the status code and URL, to HumanSecurity.BD.handleResponse. If not, the SDK won’t present a challenge to the user.

HumanSecurity.BD.handleResponse(response: string, code: number, url: string): Promise<HSBotDefenderChallengeResult>

When handling blocked requests:

  • Treat blocked requests as a failure. Your app’s UI is shown again after the user solves or cancels the challenge. If the request was triggered by a user action, make it clear that the user may try the same action again.
  • Use the promise result to log analytics, create logs, and so on.
  • (Optional) Use the returned promise to retry the original request when appropriate. Consider the following:
    • Promise scope: The promise returns outside the original request’s scope. Ensure your app handles this case correctly.
    • Challenge cancellation: The user might cancel the challenge. Do not retry the request to avoid it being blocked again.
    • Retry block possibility: The retry attempt may also be blocked. Do not assume it will succeed.
3

Set custom parameters (optional)

Custom parameters are additional custom values that you can set yourself to enrich the data you receive from HUMAN. You can have up to 10 custom parameters, and they must follow the pattern custom_paramN, where N is a number between 1 and 10. Call HumanSecurity.BD.setCustomParameters only after startWithAppId has been called.

Below is an example implementation:

import { HumanSecurity } from "@humansecurity/expo-mobile-sdk";
function setCustomParametersForBotDefender() {
const parameters = { custom_param1: "value1", custom_param2: "value2" };
try {
HumanSecurity.BD.setCustomParameters(parameters, "<APP_ID>");
console.log("Custom Parameters Set Successfully");
} catch (error) {
console.log("Failed to Set Custom Parameters");
}
}
4

Subscribe to events (optional)

Bot Defender provides several delegates, or callbacks, to notify about events related to headers and challenges. These callbacks are mainly intended for analytics and statistics rather than for taking specific actions. In the Expo library, these callbacks work as events.

To listen to an event, add a listener for it. Remove the listener when leaving the context to avoid a memory leak.

import { HumanSecurity, HS_EVENTS } from "@humansecurity/expo-mobile-sdk";
import { useEffect } from "react";
useEffect(() => {
const eventListeners = Object.values(HS_EVENTS).map((eventName) => {
console.log(`Registering listener for event: ${eventName}`);
return HumanSecurity.BD.addListener(eventName, (data) => {
handleEvent(eventName, data);
});
});
return () => {
eventListeners.forEach((subscription) => subscription.remove());
};
}, []);
const handleEvent = (eventName: string, data: any) => {
console.log(`Event Received: ${eventName}`, data);
// This is the full list of events.
switch (eventName) {
case HS_EVENTS.BOT_DEFENDER_REQUEST_BLOCKED:
console.log("Request Blocked");
break;
case HS_EVENTS.BOT_DEFENDER_CHALLENGE_SOLVED:
console.log("Challenge Solved");
break;
case HS_EVENTS.BOT_DEFENDER_CHALLENGE_CANCELLED:
console.log("Challenge Cancelled");
break;
case HS_EVENTS.BOT_DEFENDER_CHALLENGE_RENDERED:
console.log("Challenge Rendered");
break;
case HS_EVENTS.BOT_DEFENDER_CHALLENGE_RENDER_FAILED:
console.log("Challenge Render Failed");
break;
case HS_EVENTS.BOT_DEFENDER_DID_UPDATE_HEADERS:
console.log("Headers Were Updated");
break;
default:
console.log("Unknown event received:", eventName);
break;
}
};

Integrate with Account Defender

1

Enable Account Defender in your app

To enable Account Defender, set the UserID of your current logged-in user in the SDK. When the user logs out, call the function with null to clear the user ID.

Below is an example implementation:

import { HumanSecurity } from "@humansecurity/expo-mobile-sdk";
function onUserLoggedIn(userID) {
try {
HumanSecurity.AD.setUserId(userID, "<APP_ID>");
} catch (error) {
console.log(`Exception: ${error.message}`);
}
}
function onUserLoggedOut() {
try {
HumanSecurity.AD.setUserId(null, "<APP_ID>");
} catch (error) {
console.log(`Exception: ${error.message}`);
}
}
2

Notify HUMAN's backend on outgoing URL requests from the app

For Account Defender to protect the user’s account, your app has to provide the SDK with outgoing URL requests. Do this after you set the user ID. Call HumanSecurity.AD.registerOutgoingUrlRequest(url: string, appId?: string) before you send the URL request. If you use a custom HTTP client, add this function to the request interceptor.

Below is an example implementation:

import { HumanSecurity } from "@humansecurity/expo-mobile-sdk";
...
// In your sendAPIRequest function
const headers = await HumanSecurity.BD.headersForURLRequest(appId);
// Add this for account defender
HumanSecurity.AD.registerOutgoingUrlRequest(url, appId);
const response = await fetch(url, {
method: "GET",
headers,
});
...
3

Set additional data (optional)

Additional data are additional custom values that you can set yourself to enrich the data you receive from HUMAN. These are separate from custom parameters and are unique to Account Defender. Call HumanSecurity.AD.setAdditionalData(parameters: { [key: string]: string }, appId?: string) only after HumanSecurity.startWithAppId(appId: string, policy?: HSPolicy) has been called.

Below is an example implementation:

import { HumanSecurity } from "@humansecurity/expo-mobile-sdk";
function setAdditionalDataForAccountDefender() {
try {
const additionalData = {
my_key1: "hello",
my_key2: "world"
};
HumanSecurity.AD.setAdditionalData(additionalData, "<APP_ID>");
} catch (error) {
console.error(`Failed to Set Additional Data: ${error.message}`);
}
}

HUMAN Expo Mobile API reference

The HUMAN Security Expo Mobile API offers the following functions:

export declare class HumanSecurity {
static sdkVersion(): string;
static startWithAppId(appId: string, policy?: HSPolicy): Promise<void>;
static startWithAppIds(appIds: string[], policy?: HSPolicy): Promise<void>;
static vid(appId: string): string | null;
static BD: {
headersForURLRequest(appId?: string): Promise<{ [key: string]: string }>;
handleResponse(response: string, code: number, url: string): Promise<HSBotDefenderChallengeResult>;
canHandleResponse(response: string, code: number, url: string): boolean;
challengeReferenceId(): string;
setCustomParameters(parameters: {[key: string]: string}, appId?: string): void;
addListener(eventName: string, callback: (data: any) => void): import("expo-modules-core").Subscription;
};
static AD: {
setUserId(userId: string | null, appId?: string): void;
registerOutgoingUrlRequest(url: string, appId?: string): void;
setAdditionalData(parameters: {[key: string]: string}, appId?: string): void;
};
}