Skip to navigation

React Native integration (recommended)

Learn how to integrate the HUMAN React Native wrapper into a React Native 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 a React Native project to integrate the HUMAN React Native wrapper into a React Native application.

Integrate the HUMAN React Native wrapper

  1. In the terminal from the command line, run:
npm install @humansecurity/react-native-sdk
  1. If your app uses iOS, navigate to the ios folder and install pods.
cd ios
pod install

Start the SDK

When starting the SDK, start the SDK as soon as possible, and only once. Call startWithAppId in your main entry point (App.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 HumanSecurity from '@humansecurity/react-native-sdk';
// Initialize the SDK once on app startup
(() => {
HumanSecurity.startWithAppId("<APP_ID>") // update with your own 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 our Sensor. In this case, configure all relevant website domains with the Application ID. Hybrid is supported for react-native-webview when webRootDomains is set. Set webRootDomains to the bare registrable root (example.com). A leading dot is accepted and equivalent. Do not list www or a subdomain. This wrapper 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 to the SDK. Call canHandleResponse. If it returns true, call handleResponse to present the challenge. Pass the arguments correctly. When using Axios, call JSON.stringify(error.response?.data) before passing the response body, 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.
    • CANCELED: 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/react-native-sdk';
public static async fetchData(url: string): Promise<any> {
try {
const headers = HumanSecurityManager.getHeaders();
const response = await fetch(url, { method: 'GET', headers });
const statusCode = response.status;
const responseText = await response.text();
if (statusCode === 200) {
return { status: statusCode, data: responseText };
}
if (HumanSecurityManager.canHandleResponse(responseText)) {
const result = await HumanSecurityManager.handleResponse(responseText);
// If challenge was solved, retry the request.
return { challengeResult: HSBotDefenderChallengeResult[result] };
}
throw new Error(`Unhandled response - Status: ${statusCode}`);
} catch (error) {
throw error instanceof Error ? error : new Error('Unknown error occurred');
}
}
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 to HumanSecurity.BD.handleResponse. If not, the SDK won’t present a challenge to the user.

HumanSecurity.BD.handleResponse(response: 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/react-native-sdk';
const setCustomParams = () => {
const parameters = { custom_param1: 'value1', custom_param2: 'value2' };
HumanSecurity.BD.setCustomParameters(parameters, appId)
.then(() => {
setCustomParamsResult('Custom Parameters Set Successfully');
})
.catch((error) => {
setCustomParamsResult('Failed to Set Custom Parameters: ' + error);
});
};
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 for Bot Defender events, subscribe to the onBotDefenderEvent listener. The received event will be of type BotDefenderEvent and can be handled as needed.

useEffect(() => {
const subscription = HumanSecurity.BD.onBotDefenderEvent((event) => {
console.log(
`[HumanSdk] Event received: ${event.event} | AppID: ${event.appId} | Headers: ${JSON.stringify(event.headers)}`
);
});
return () => {
subscription.remove();
};
}, []);

Only the botDefenderDidUpdateHeaders event provides headers. The rest provide the Application ID.

export interface BotDefenderEvent {
event:
| 'botDefenderRequestBlocked'
| 'botDefenderChallengeSolved'
| 'botDefenderChallengeCancelled'
| 'botDefenderChallengeRendered'
| 'botDefenderChallengeRenderFailed'
| 'botDefenderDidUpdateHeaders';
appId: string;
headers?: { [key: string]: string };
}

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/react-native-sdk';
const setUserId = (userId: string) => {
HumanSecurity.AD.setUserId(userID, "<APP_ID>") // update with your app ID
.then(() => {
setUserIdResult('User ID Set Successfully');
})
.catch((error) => {
setUserIdResult('Failed to Set User ID: ' + error);
});
};
function onUserLoggedOut() {
try {
HumanSecurity.AD.setUserId(null, "<APP_ID>"); // update with your 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/react-native-sdk";
...
// In your sendAPIRequest function
const headers = await HumanSecurity.BD.headersForURLRequest(appId);
// Add this for account defender
HumanSecurity.AD.registerOutgoingUrlRequest(url, appId).catch((error) => {
console.log('Error registering outgoing url request: ', error);
});
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/react-native-sdk";
const setAdditionalData = async () => {
const parameters = { key1: 'value1', key2: 'value2' };
HumanSecurity.AD.setAdditionalData(parameters, appId).then(
() => {
setAdditionalDataResult('Additional Data Set Successfully');
},
(error) => {
setAdditionalDataResult('Failed to Set Additional Data' + error);
}
);
};

HUMAN React Native API reference

The HUMAN Security React Native Wrapper 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 }>;
canHandleResponse(response: string): boolean;
handleResponse(response: string): Promise<HSBotDefenderChallengeResult>;
challengeReferenceId(): string;
setCustomParameters(parameters: { [key: string]: string }, appId?: string): Promise<void>;
onBotDefenderEvent(fn: BotDefenderEventCallback): EventSubscription;
};
static AD: {
setUserId(userId: string | null, appId?: string): Promise<void>;
registerOutgoingUrlRequest(url: string, appId?: string): Promise<void>;
setAdditionalData(parameters: { [key: string]: string }, appId?: string): Promise<void>;
};
}