Skip to navigation

React Native integration (legacy)

Learn how to integrate the mobile SDK with your React Native app using our legacy implementation.

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 learn how to integrate the SDK with a React Native project with this guide.

This integration is the legacy version. For the most recent version, see our recommended integration.

1

Add the -fcxxmodules flag (iOS C++ projects only)

If your project is built with C++ (AppDelegate.mm), do the following:

  1. Open Xcode Build Settings.
  2. Navigate to Targets > Build Settings > Apple Clang - Custom Compiler Flags > Other C++ Flags.
  3. Add the -fcxx-modules flag.
2

Add the Human Module

  1. Create a native module called HumanModule.

Add a package declaration at the top of each Java file matching your project’s package name (e.g. package com.yourapp;).

Java (HumanModule.java)
import androidx.annotation.NonNull;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.humansecurity.mobile_sdk.HumanSecurity;
import com.humansecurity.mobile_sdk.main.HSBotDefenderChallengeResult;
import org.json.JSONObject;
import java.util.HashMap;
public class HumanModule extends ReactContextBaseJavaModule {
static HumanModule shared = null;
String strNewHeaders = "HumanNewHeaders";
String strChallengeResult = "HumanChallengeResult";
String strSolved = "solved";
String strCancelled = "cancelled";
String strFalse = "false";
HumanModule(ReactApplicationContext context) {
super(context);
}
@NonNull
@Override
public String getName() {
return "HumanModule";
}
public void handleUpdatedHeaders(HashMap<String, String> headers) {
if (!this.getReactApplicationContext().hasCatalystInstance()) {
return;
}
JSONObject json = new JSONObject(headers);
this.getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(strNewHeaders, json.toString());
}
public void handleChallengeSolvedEvent() {
if (!this.getReactApplicationContext().hasCatalystInstance()) {
return;
}
this.getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(strChallengeResult, strSolved);
}
public void handleChallengeCancelledEvent() {
if (!this.getReactApplicationContext().hasCatalystInstance()) {
return;
}
this.getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(strChallengeResult, strCancelled);
}
@ReactMethod
public void addListener(String eventName) {
}
@ReactMethod
public void removeListeners(Integer count) {
}
@ReactMethod
public void getHTTPHeaders(Promise promise) {
JSONObject json = new JSONObject(HumanSecurity.INSTANCE.getBD().headersForURLRequest(null));
promise.resolve(json.toString());
}
@ReactMethod
public void handleResponse(String response, Integer code, String url, Promise promise) {
boolean handled = HumanSecurity.INSTANCE.getBD().handleResponse(response, result -> {
promise.resolve(result == HSBotDefenderChallengeResult.SOLVED ? strSolved : strCancelled);
return null;
});
if (!handled) {
promise.resolve(strFalse);
}
}
}
  1. Add the HumanModule to the HumanPackage and set the shared property.
Java (HumanPackage.java)
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HumanPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
HumanModule module = new HumanModule(reactContext);
HumanModule.shared = module;
modules.add(module);
return modules;
}
}
3

Start the SDK

When starting the SDK, keep the following in mind:

  1. Start the SDK as soon as possible in your app’s flow. We recommend doing so in the Application’s onCreate function in Android or the AppDelegate’s didFinishLaunchingWithOptions function in iOS. If you don’t do this, then your application may send a URL request to your server before the SDK starts. This means the request will not include HTTP headers that indicate whether the request is legitimate, and as a result:
    • The Enforcer may block the request instead, and
    • The SDK will not be able to present a challenge to the user
  2. Start the SDK on the main thread.
  3. Implement the HumanDelegate to receive events from the SDK.

Below are example implementations for both Android and iOS:

Don’t forget to replace <APP_ID> with your actual Application ID, and <YOUR_APP_NAME> with your React Native module name (as registered in AppRegistry).

Java (MainApplication.java)
import android.app.Application;
import java.util.HashMap;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactNativeHost;
import com.facebook.react.soloader.OpenSourceMergedSoMapping;
import com.facebook.soloader.SoLoader;
import com.humansecurity.mobile_sdk.HumanSecurity;
import com.humansecurity.mobile_sdk.main.HSBotDefenderDelegate;
import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType;
import com.humansecurity.mobile_sdk.main.policy.HSPolicy;
public class MainApplication extends Application implements ReactApplication, HSBotDefenderDelegate {
private final ReactNativeHost mReactNativeHost =
new DefaultReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new HumanPackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
@Override
protected boolean isNewArchEnabled() {
return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
}
@Override
protected Boolean isHermesEnabled() {
return BuildConfig.IS_HERMES_ENABLED;
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
try {
SoLoader.init(this, OpenSourceMergedSoMapping.INSTANCE);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
DefaultNewArchitectureEntryPoint.load();
}
HSPolicy policy = new HSPolicy();
policy.getAutomaticInterceptorPolicy().setInterceptorType(HSAutomaticInterceptorType.NONE);
try {
HumanSecurity.INSTANCE.start(this, "<APP_ID>", policy);
HumanSecurity.INSTANCE.getBD().setDelegate(this);
} catch (Exception exception) {
exception.printStackTrace();
}
}
@Override
public void botDefenderDidUpdateHeaders(@NonNull HashMap<String, String> headers, @NonNull String appId) {
if (HumanModule.shared != null) {
HumanModule.shared.handleUpdatedHeaders(headers);
}
}
@Override
public void botDefenderRequestBlocked(@Nullable String url, @NonNull String appId) {
}
@Override
public void botDefenderChallengeSolved(@NonNull String appId) {
HumanModule.shared.handleChallengeSolvedEvent();
}
@Override
public void botDefenderChallengeCancelled(@NonNull String appId) {
HumanModule.shared.handleChallengeCancelledEvent();
}
@Override
public void botDefenderChallengeRendered(@NonNull String appId) {
}
@Override
public void botDefenderChallengeRenderFailed(@NonNull String appId) {
}
}

In particular, note the following:

  1. Initialization: We start the SDK as soon as possible and on the main thread to ensure all URL requests include the necessary HTTP headers.
  2. Policy configuration: We create a HSPolicy instance to configure the SDK’s behavior. In this case, we set the interceptorType property to HSAutomaticInterceptorType.NONE to disable the automatic interception feature, which is not supported in React Native.
  3. Start the SDK: We call the HumanSecurity.start(appId, policy) function of the SDK with:
    • The Application instance (Android only).
    • Your Application ID. If you have multiple IDs, see our guide on how to handle them.
    • The policy object.
  4. On iOS, we call the startObserving function on the HumanModule.
  5. On Android, we use SoLoader.init(this, OpenSourceMergedSoMapping.INSTANCE) for proper native library loading (required for React Native 0.73+).
  6. On iOS, AppDelegate extends RCTAppDelegate (required for React Native 0.73+). Set self.moduleName and self.initialProps, then call [super application:application didFinishLaunchingWithOptions:launchOptions] to configure React Native.
4

Add HTTP headers and handle block response

In your JavaScript code:

  1. Import the HumanModule.
  2. Create a new native event emitter.
  3. Add a listener to the New Headers event.
  4. Add a listener to the Challenge Result event.
  5. Add the SDK’s HTTP headers to your URL requests.
  6. When a request is blocked, send the block response to the SDK.
  7. Handle the challenge’s result.
/* Import HumanModule */
import { NativeModules, NativeEventEmitter } from 'react-native';
const { HumanModule } = NativeModules;
/* Create a new native event emitter */
const humanEventEmitter = new NativeEventEmitter(HumanModule);
/* Add listener to the "New Headers" event and store the SDK's HTTP headers in a variable */
let humanHttpHeaders = null;
const onNewHeaders = headers => {
const obj = JSON.parse(headers);
console.log(`Got new HTTP headers: ${JSON.stringify(obj)}`);
humanHttpHeaders = obj;
};
const subscriptionHumanNewHeaders = humanEventEmitter.addListener('HumanNewHeaders', onNewHeaders);
/* Add listener to the "Challenge Result" event */
const onChallengeResult = result => {
if (result === 'solved') {
console.log('Challenge solved');
} else if (result === 'cancelled') {
console.log('Challenge cancelled');
}
};
const subscriptionHumanChallengeResult = humanEventEmitter.addListener('HumanChallengeResult', onChallengeResult);
/* Get Human's HTTP headers */
const getHumanHeaders = async () => {
if (humanHttpHeaders != null) {
return humanHttpHeaders;
}
const headers = await HumanModule.getHTTPHeaders();
const obj = JSON.parse(headers);
console.log(`[HUMAN] Got HTTP headers: ${JSON.stringify(obj)}`);
return obj;
};
/* Send URL request */
async function sendRequest(url) {
/* Get Human's HTTP headers */
const humanHeaders = await getHumanHeaders();
try {
const response = await fetch(url, {
method: 'GET',
headers: humanHeaders,
});
const json = await response.json();
/* Send the response to the SDK */
const result = await HumanModule.handleResponse(JSON.stringify(json), response.status, url);
if (result === 'solved') {
console.log('Challenge solved');
await sendRequest(url);
} else if (result === 'cancelled') {
console.log('Challenge cancelled');
} else if (result === 'false') {
console.log('Request was not blocked by Human');
}
} catch (error) {
console.error(error);
}
}
5

Pass the block response

When the HUMAN 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 whole JSON to the SDK via the HSBotDefender/handleResponse(response:data:callback:) function. Otherwise, the SDK won’t present a challenge to the user.