> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# React Native integration (legacy)

> **Note**
>
> 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](/applications/ios-how-to-integrate-the-sdk-in-your-application-v3) or [Android](/applications/android-how-to-integrate-the-sdk-in-your-application-v3) documentation.

You can learn how to integrate the SDK with a [React Native](https://reactnative.dev/) project with this guide.

> **Warning**
>
> This integration is the legacy version. For the most recent version, see our [recommended integration](/applications/sdk/v4/react-native-integration-recommended).

#### 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.

#### Add the Human Module

#### Android

1. Create a [native module](https://reactnative.dev/docs/legacy/native-modules-android) called `HumanModule`.

> **Note**
>
> 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)`**

```java title="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);
        }
    }
}
```

2. Add the `HumanModule` to the `HumanPackage` and set the `shared` property.

**`Java (HumanPackage.java)`**

```java title="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;
    }
}
```

#### iOS

Create a [native module](https://reactnative.dev/docs/legacy/native-modules-ios) called `HumanModule`.

**`Objective-C (HumanModule.h)`**

```c title="Objective-C (HumanModule.h)"
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

NS_ASSUME_NONNULL_BEGIN

@interface HumanModule : RCTEventEmitter <RCTBridgeModule>

+ (HumanModule *)shared;
- (void)handleUpdatedHeaders:(NSDictionary<NSString *,NSString *> *)headers;
- (void)handleChallengeSolvedEvent;
- (void)handleChallengeCancelledEvent;

@end

NS_ASSUME_NONNULL_END
```

**`Objective-C (HumanModule.m)`**

```c title="Objective-C (HumanModule.m)"
#import "HumanModule.h"
@import HUMAN;

static NSString *strNewHeaders = @"HumanNewHeaders";
static NSString *strChallengeResult = @"HumanChallengeResult";
static NSString *strSolved = @"solved";
static NSString *strCancelled = @"cancelled";
static NSString *strFalse = @"false";

@implementation HumanModule

static HumanModule *shared = nil;

+ (HumanModule *)shared {
  return shared;
}

+ (BOOL)requiresMainQueueSetup {
  return YES;
}

- (instancetype)init {
  self = [super init];
  shared = self;
  return self;
}

- (NSArray<NSString *> *)supportedEvents {
  return @[strNewHeaders, strChallengeResult];
}

- (void)handleUpdatedHeaders:(NSDictionary<NSString *,NSString *> *)headers {
  NSData *data = [NSJSONSerialization dataWithJSONObject:headers options:0 error:nil];
  NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  [self sendEventWithName:strNewHeaders body:json];
}

- (void)handleChallengeSolvedEvent {
  [self sendEventWithName:strChallengeResult body:strSolved];
}

- (void)handleChallengeCancelledEvent {
  [self sendEventWithName:strChallengeResult body:strCancelled];
}

RCT_EXPORT_MODULE(HumanModule);

RCT_REMAP_METHOD(getHTTPHeaders,
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject) {
  NSDictionary<NSString *, NSString *> *humanHttpHeaders = [HumanSecurity.BD headersForURLRequestForAppId:nil];
  NSData *data = [NSJSONSerialization dataWithJSONObject:humanHttpHeaders options:0 error:nil];
  NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  resolve(@[json]);
}

RCT_REMAP_METHOD(handleResponse,
                 response:(NSString *)response
                 code:(NSInteger)code
                 url:(NSString *)url
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject) {
  NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
  NSHTTPURLResponse *httpURLResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:url] statusCode:code HTTPVersion:nil headerFields:nil];
  BOOL handled = [HumanSecurity.BD handleResponseWithResponse:httpURLResponse data:data callback:^(enum HSBotDefenderChallengeResult result) {
    resolve((result == HSBotDefenderChallengeResultSolved ? strSolved : strCancelled));
  }];
  if (!handled) {
    resolve(strFalse);
  }
}

@end
```

#### 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:

> **Note**
>
> 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`).

#### Android

**`Java (MainApplication.java)`**

```java title="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) {
    }
}
```

#### iOS

**`Objective-C (AppDelegate.h)`**

```c title="Objective-C (AppDelegate.h)"
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
@import HUMAN;

@interface AppDelegate : RCTAppDelegate <HSBotDefenderDelegate>

@end
```

**`Objective-C (AppDelegate.m)`**

```c title="Objective-C (AppDelegate.m)"
#import "AppDelegate.h"
#import "HumanModule.h"

#import <React/RCTBundleURLProvider.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"<YOUR_APP_NAME>";
  self.initialProps = @{};

  HSPolicy *policy = [[HSPolicy alloc] init];
  policy.automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorTypeNone;
  NSError *error = nil;
  [HumanSecurity startWithAppId:@"<APP_ID>" policy:policy error:&error];
  HumanSecurity.BD.delegate = self;
  if (error != nil) {
    NSLog(@"failed to start. error: %@", error.localizedDescription);
  }

  BOOL result = [super application:application didFinishLaunchingWithOptions:launchOptions];

  [[HumanModule shared] startObserving];

  return result;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
  return [self bundleURL];
}

- (NSURL *)bundleURL
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

// MARK: - HSBotDefenderDelegate

- (void)botDefenderDidUpdateHeaders:(NSDictionary<NSString *,NSString *> *)headers forAppId:(NSString *)appId {
  if ([HumanModule shared] != nil) {
    [[HumanModule shared] handleUpdatedHeaders:headers];
  }
}

- (void)botDefenderChallengeSolvedForAppId:(NSString *)appId {
  [[HumanModule shared] handleChallengeSolvedEvent];
}

- (void)botDefenderChallengeCancelledForAppId:(NSString *)appId {
  [[HumanModule shared] handleChallengeCancelledEvent];
}

- (void)botDefenderChallengeRenderedForAppId:(NSString *)appId {
}

- (void)botDefenderChallengeRenderFailedForAppId:(NSString *)appId {
}

@end
```

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](/applications/sdk/v4/getting-started#handle-multiple-application-ids) 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.

#### 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.

```javascript
/* 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);
  }
}
```

#### 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:

```json
{
  "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.