Integration with React Native
  • 09 Nov 2023
  • Dark
    Light

Integration with React Native

  • Dark
    Light

Article Summary

v2.x

The SDK can be integrated into React Native projects.

  1. Add the SDK to your Android project as described above.
  2. The automatic interceptor is not supported in React Native, so any request from the JavaScript code has to be handled manually.
  3. Disable the automatic interception as described above.
  4. Create a native module as described here.
  5. Create a function that pass the HTTP headers from the HUMAN SDK to the JavaScript code. Here is an example:
    RCT_EXPORT_METHOD(getHTTPHeaders:(RCTResponseSenderBlock)callback) {
        NSDictionary<NSString *, NSString *> *headers = [PerimeterX headersForURLRequestForAppId:nil];
        NSData *data = [NSJSONSerialization dataWithJSONObject:headers options:0 error:nil];
        NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        callback(@[json]);
    }
    
  6. In your JavaScript code, send your request with those HTTP headers. Here is an example:
    PerimeterXModule.getHTTPHeaders(async headers => {
        const obj = JSON.parse(headers);
        const url = 'https://my.request.com'
        const response = await fetch(url, {
            method: 'GET',
            headers: obj,
        })
    });
    
  7. Next, pass the response back to the native module. Here is an example:
    RCT_EXPORT_METHOD(handleResponse:(NSString *)response code:(NSInteger)code url:(NSString *)url) {
        NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
        NSHTTPURLResponse *httpURLResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:url] statusCode:code HTTPVersion:nil headerFields:nil];
        [PerimeterX handleResponseForAppId:nil data:data response:httpURLResponse];
    }
    
    const json = await response.json();
    PerimeterXModule.handleResponse(JSON.stringify(json), response.status, url);
    

Was this article helpful?