React Native integration

Updated at:

The client integration overview explains the basic principles of HTTPDNS integration. This guide explains how to integrate and use the Alibaba Cloud HTTPDNS React Native plugin in your React Native application.

The React Native plugin encapsulates the native Android and iOS HTTPDNS SDKs and provides a unified JavaScript API to initialize HTTPDNS and configure features in your React Native application.

1. Quick start

1.1 Enable the service

See Quick start to enable HTTPDNS.

1.2 Get configuration details

See Development Configurations to obtain your account ID, secret key, and AES secret key from the EMAS console. This information is required to initialize the SDK.

2. Installation and configuration

2.1 Install the plugin

In the root directory of your React Native project, run the following command:

npm install @alicloud-emas/httpdns-react-native

If you use Yarn:

yarn add @alicloud-emas/httpdns-react-native

2.2 Android configuration

No additional native code configuration is required for Android.

The plugin uses a ContentProvider to automatically inject a custom DNS resolver into the OkHttpClient used by the React Native networking stack early in the application startup process. You can continue to use your existing network request code without changes.

If your project has code obfuscation enabled, add the following rule to your Android project's ProGuard or R8 configuration:

-keep class com.alibaba.sdk.android.**{*;}

2.3 iOS configuration

2.3.1 Configure CocoaPods sources

The HTTPDNS iOS SDK and EMASCurl are published to the Alibaba Cloud CocoaPods repository. Add the following sources to the top of your iOS project's Podfile:

source 'https://github.com/aliyun/aliyun-specs.git'
source 'https://github.com/CocoaPods/Specs.git'

Then, run the following commands:

cd ios
pod install

2.3.2 Inject into the networking stack

On iOS, you need to call the installation method once in your AppDelegate.m or AppDelegate.mm file:

#import <httpdns-react-native/AliyunHttpDnsRN.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [AliyunHttpDnsRN install];

  // Other React Native initialization code
  return YES;
}

This method uses RCTSetCustomNSURLSessionConfigurationProvider to inject HTTPDNS into React Native's network requests.

3. Initialization and usage

3.1 Pre-initialization configuration

The plugin follows a "configure first, then initialize" pattern. We recommend applying the following settings before calling init. The init method then uses these configurations to build the HTTPDNS service instance.

import * as AliyunHttpDns from '@alicloud-emas/httpdns-react-native';

AliyunHttpDns.setHttpsRequestEnabled(true);
AliyunHttpDns.setReuseExpiredIPEnabled(true);

await AliyunHttpDns.init({
  accountId: 123456,
  secretKey: 'your_secret_key',
});
Important
  • Enabling setHttpsRequestEnabled(true) incurs additional charges. For details, see the Billing documentation.

  • If you require enhanced security for your domain information, you can configure an aesSecretKey to enable content-layer encryption for resolution requests. Using AES content encryption incurs additional charges. Before enabling this feature, carefully review the Billing documentation.

3.2 Configure domain pre-resolution

After initialization, you can configure pre-resolution for hot domains to reduce the resolution latency for subsequent requests.

AliyunHttpDns.setPreResolveHosts(['www.aliyun.com'], 'auto');

3.3 Make network requests

After initialization, the plugin automatically integrates HTTPDNS with the React Native networking stack. When you use fetch, XMLHttpRequest, Axios, or other libraries based on the React Native networking module, you do not need to manually call the resolution API. You can continue to make network requests as you normally would:

import axios from 'axios';

// Using fetch
const response = await fetch('https://www.aliyun.com');

// Using Axios
const axiosResponse = await axios.get('https://www.aliyun.com');

4. Notes

  1. On Android, the plugin uses a ContentProvider to automatically inject a custom DNS resolver into the OkHttpClient used by the React Native networking stack. You do not need to modify MainApplication or manually adapt OkHttp.

  2. On iOS, you must call [AliyunHttpDnsRN install] in your AppDelegate. The plugin uses EMASCurl to integrate with the React Native networking stack. For more information about the capabilities of EMASCurl, see EMASCurl.

  3. By default, the plugin uses synchronous, non-blocking resolution in the networking stack. It prioritizes returning cached results. If a result is not in the cache or is unavailable, the request is not blocked; instead, it falls back to the underlying layer for processing.

5. API

5.1 init

Builds the HTTPDNS service instance. Ensure that you complete initialization before using any HTTPDNS resolution capabilities. We recommend calling this method during your application's startup phase. The React Native plugin applies all pre-configured settings to the underlying Android or iOS HTTPDNS SDK during initialization.

const success = await AliyunHttpDns.init({
  accountId: 123456,
  secretKey: 'your_secret_key', // Optional, configure if authentication is enabled
  aesSecretKey: 'your_aes_secret_key', // Optional, configure if encryption is enabled
});

Parameters:

Parameter

Type

Required

Description

accountId

number

Yes

Your HTTPDNS account ID.

secretKey

string

No

The secret key for authentication.

aesSecretKey

string

No

The encryption key.

Return value:

Type

Description

Promise<boolean>

true means that the initialization succeeded, and false means that it failed.

5.2 setLogEnabled

Enables or disables local debug logging. You can enable debug logs to troubleshoot resolution issues. We recommend disabling this feature in production environments.

AliyunHttpDns.setLogEnabled(true);

5.3 setHttpsRequestEnabled

Specifies whether the SDK uses HTTPS for its internal resolution requests to the server. If this method is not called, the SDK uses HTTP by default.

AliyunHttpDns.setHttpsRequestEnabled(true);

5.4 setPersistentCacheIPEnabled

Enables or disables the persistent cache. This feature optimizes domain name resolution time on application startup, which helps improve first-screen load times.

When enabled, HTTPDNS saves the last known resolution results to local persistent storage. After the app restarts, the first resolution for each domain will prioritize retrieving results from this persistent layer for faster resolution.

AliyunHttpDns.setPersistentCacheIPEnabled(true);
AliyunHttpDns.setPersistentCacheIPEnabled(true, 86400);

Parameters:

Parameter

Type

Required

Description

enabled

boolean

Yes

Specifies whether to enable the persistent cache.

discardExpiredAfterSeconds

number

No

After the app starts, this setting discards any record loaded from the persistent cache that has been expired for longer than the specified duration. Unit: seconds.

5.5 setReuseExpiredIPEnabled

Specifies whether the resolution API can return cached resolution results that have exceeded their Time-to-Live (TTL).

When enabled and a cached IP has expired, the SDK can immediately return the stale IP to reduce DNS processing time, while asynchronously refreshing the resolution result for that domain.

AliyunHttpDns.setReuseExpiredIPEnabled(true);

5.6 setPreResolveAfterNetworkChanged

Specifies whether to automatically refresh domain resolution results after the network environment changes.

The SDK listens for network change events and manages the cache according to its policy. If this feature is enabled, the SDK automatically refreshes resolution results after a network switch, which reduces domain name resolution time and improves request performance.

AliyunHttpDns.setPreResolveAfterNetworkChanged(true);

5.7 setRegion

Sets the HTTPDNS bootstrap service node. If your app needs to use HTTPDNS in an overseas environment, you can explicitly set the bootstrap service node. The SDK then uses the specified node for domain name resolution and subsequent updates to the scheduling node list.

AliyunHttpDns.setRegion('cn');

Valid values are cn, hk, sg, de, and us. By default, this does not need to be set, as the SDK automatically selects a node based on the client's network.

5.8 setTimeoutInterval

Sets the timeout for domain name resolution requests, in seconds. This setting only affects the HTTPDNS SDK's resolution requests to the server and does not affect the timeout of your application's network requests.

AliyunHttpDns.setTimeoutInterval(2);

5.9 setIPRankingList

Enables IP ranking. After you specify a service's probing port for a domain, the SDK performs TCP connection probing on the IPs returned by resolution. It then dynamically sorts the IP list based on the probing results.

The IP list obtained immediately after the first HTTPDNS resolution might not be sorted. This feature is suitable for domains that are sensitive to connection latency. Before enabling it, evaluate its impact based on your business traffic and server load.

AliyunHttpDns.setIPRankingList({'www.aliyun.com': 443,});

5.10 configCacheTtlChanger

Customizes the TTL for resolution results. By default, the HTTPDNS SDK uses the TTL value from the domain resolution result as the cache duration. You can use this API to specify a custom TTL for different domains, which changes how long the SDK caches their resolution results.

AliyunHttpDns.configCacheTtlChanger({'www.aliyun.com': 300,});

5.11 setPreResolveHosts

Sets a list of domains for pre-resolution. After your app starts and the SDK is initialized, you can call this API to set hot domains that are likely to be used. The SDK then resolves them in advance, which reduces the latency of subsequent domain name resolution requests.

If you call this API while the application is running, the SDK immediately resolves the specified domains, refreshing their resolution results and storing them in the cache.

AliyunHttpDns.setPreResolveHosts(['www.aliyun.com'], 'auto');

Parameters:

Parameter

Type

Required

Description

hosts

string[]

Yes

A list of domains for pre-resolution.

ipType

string

No

auto, ipv4, ipv6, or both. The default value is auto.

Note

The hosts array should contain only domain name strings, without any protocol prefixes (such as https://), paths, or ports.

5.12 getSessionId

Gets the current HTTPDNS session ID. This ID can be used for troubleshooting and log correlation.

const sessionId = await AliyunHttpDns.getSessionId();

Return value:

Type

Description

Promise<string | null>

The current session ID, or null if it fails to be initialized or retrieved.

5.13 cleanHostCache

To clear the cache for specific domains, pass them in an array. To clear the entire cache, call the method without arguments or with an empty array.

// Clear the entire cache
AliyunHttpDns.cleanHostCache();
// Clear the cache for a specific domain
AliyunHttpDns.cleanHostCache(['www.aliyun.com']);

5.14 setAuthCurrentTime

Corrects the app's signing time for authentication. In authentication mode, an inaccurate device time can cause authentication to fail. After you call this API, the SDK corrects the signing time for subsequent requests based on the provided time.

This correction is only valid for the current application lifecycle and must be reapplied after the app restarts.

const currentTime = Math.floor(Date.now() / 1000);
AliyunHttpDns.setAuthCurrentTime(currentTime);

The time parameter is a Unix timestamp in seconds.

6. Summary

This guide explains how to use the HTTPDNS plugin in a React Native environment. The plugin automatically integrates with the React Native networking stack, so you can use HTTPDNS capabilities without modifying your application's request code. Key features include:

  1. Simple integration: Initialize and configure features through a JavaScript API.

  2. Seamless integration: Standard React Native network requests use HTTPDNS automatically without requiring manual API calls.

  3. Full-featured: Supports caching, pre-resolution, IP ranking, and more.

By following this guide, you can efficiently integrate the HTTPDNS service into your React Native applications.