At a glance: Integrate AppsFlyer SDK into iOS/Android apps developed with React Native to measure installs, in-app events, media sources, and more.
Important!
React Native V6 plugin
A React Native V6 plugin is available, helping app owners and developers prepare for iOS 14, and providing app attribution and event reporting functionality to Android and iOS mobile apps. The plugin is functionally equivalent to the AppsFlyer iOS and Android SDKs.
The plugin is open-source and available on GitHub.
To update your plugin from an earlier version:
- Remove the earlier plugin and replace it following the instruction in our GitHub guide.
- Change the integration code by renaming and deleting the necessary APIs.
Deprecated versions
To learn about which plugin versions are deprecated, how it affects you, and how to update to the latest SDK version, click here.
1. Overview
AppsFlyer's React Native plugin adds SDK functionality when you build your app. Record installs, updates, and sessions as well as in-app events (such as in-app purchases, game levels, etc.) and use them to evaluate ROI and user-engagement levels.
To learn more, visit the node package manager (npm) page for the AppsFlyer React Native plugin.
1.1 SDK integration overview
Tab | Purpose | Result |
---|---|---|
[Mandatory] |
How to add and configure the SDK. |
App dashboard shows:
|
[Recommended] Core APIs |
How to use plugin core APIs.
|
App dashboard shows:
Ready to:
|
Additional APIs |
How to implement and use optional APIs for:
|
Ready to:
|
API reference |
Quick plugin API reference for developers |
1.2 Plugin compatibility
The latest version of the React Native plugin is built with:
- iOS: AppsFlyer SDK V6.2.3
- Android: AppsFlyer SDK V6.2.0
After you implement and initialize the React Native plugin, you'll see two installs in your app's AppsFlyer dashboard—one organic, the other non-organic.
2. Install the plugin
These instructions apply to apps that support auto-linking. The plugin uses auto-linking from:
- React Native v0.60
- react-native-appsflyer v1.4.7
If your app doesn't support auto-linking, see this installation guide.
To install the plugin:
- Download the library from npm:
$ npm install react-native-appsflyer --save
- Run the relevant set of commands: Android or iOS
$ react-native run-android
$ cd ios && pod install
$ react-native run-ios
3. Implement and initialize the plugin
This section describes how to implement and initialize the React Native plugin.
3.1 Retrieve your dev key
Your AppsFlyer dev key is unique and identifies your account. Its use is mandatory as it allows the SDK to securely send and retrieve data belonging to your AppsFlyer account. Only your Admin can retrieve the dev key.
To retrieve a dev key:
- Go to the AppsFlyer platform.
- In the menu bar, go to Configuration and click App settings.
- Under SDK installation, copy the dev key shown in the field.
3.2 Initialize the plugin
To initialize the plugin:
- In app.js, import the following:
import appsFlyer from 'react-native-appsflyer';
- Call the initSDK method using these parameters:
Parameter | Type | Description |
---|---|---|
options |
Object |
SDK configuration |
onSuccess |
Function |
Returns callback object |
onError |
Function |
Returns callback object |
Options
Name | Type | Default | Description |
---|---|---|---|
devKey |
string |
AppsFlyer dev key | |
appId |
string |
[iOS only] Apple Application ID | |
isDebug |
boolean |
false |
[Optional] Debug mode |
Example: Initialize the plugin
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import appsFlyer from 'react-native-appsflyer';
appsFlyer.initSdk(
{
devKey: 'K2***********99',
isDebug: false, // set to true if you want to see data in the logs
appId: '4*******4', // iOS app id
},
(result) => {
console.log(result);
},
(error) => {
console.error(error);
}
);
4. Test installs
You've built your app, now it's time to test the plugin. Follow the relevant operating system (OS) instructions:
Measure the quality of your users by recording in-app events and revenue, and give them a better user experience with deep linking.
This tab has instructions for developers, but marketer input is essential as they:
- Decide which in-app events need to be recorded to measure user quality.
- Access AppsFlyer dashboards to set up OneLink for deep linking.
5. Record in-app events
Recommended practice! Define the events you want to record.
In-app events offer insight into app activities. For example, record in-app events to measure KPI such as ROI (Return on Investment) and LTV (Lifetime Value).
There are several ways to record in-app events; this article sets out the most common way which is to send events via the SDK. The In-app events overview guide details other ways to record in-app events.
If an app belongs to a certain vertical such as travel, gaming, eCommerce, etc., then see the full list of recommended in-app events per vertical.
5.1 Names and parameters
To record in-app events, use this list of recommended event names and parameters.
Recommended practice! Use event names and parameters for the following reasons:
- Standard naming: AppsFlyer can automatically map events to SRNs such as Facebook, Google, Twitter, and Snapchat.
- Backward compatibility: No issue arises if AppsFlyer changes an event name or parameter as your implementation is backward compatible.
5.2 Record in-app events
Use the logEvent
method to record in-app events.
logEvent Parameters
Parameter | Type | Description |
---|---|---|
eventName |
String |
Custom event name is presented in your dashboard. See the event list here. |
eventValue |
Object |
Event details |
Example
const eventName = "af_add_to_cart";
const eventName = "af_add_to_cart";
const eventValues = {
af_content_id: "id123",
};
appsFlyer.logEvent(
eventName,
eventValues,
(res) => {
console.log(res);
},
(err) => {
console.error(err);
}
);
5.3 Record revenue
Send revenue with any in-app event by using the af_revenue
event parameter.
- Populate
af_revenue
with any numeric value, positive or negative. af_revenue
is the only event parameter considered as real revenue in raw data reports and on the dashboard. Click here for more details.
Learn more about currency settings, display, and currency conversion.
Consider these currency code factors when sending events with revenue:
- Default currency: USD
- Set currency codes as a 3 character ISO 4217 code.
- Revenue values cannot contain comma separators, currency symbols, or text.
Example revenue event: 1234.56
Example: Record an in-app event with revenue
const eventName = "purchase";
const eventValues = {
"af_content_id": "id123",
"af_currency":"USD",
"af_revenue": "2"
};
appsFlyer.logEvent(eventName, eventValues, (error, result) => {
if (error) {
console.error(error);
} else {
//...
}
});
5.4 Record negative revenue
Sometimes it is necessary to record negative revenue, such as when giving a user a refund on a purchase.
const eventName = "refund";
const eventValues = {
"af_content_id": "id123",
"af_currency":"USD",
"af_revenue": "-2" // The revenue value is preceded by a minus sign.
};
appsFlyer.logEvent(eventName, eventValues, (error, result) => {
if (error) {
console.error(error);
} else {
//...
}
});
5.5 In-app event considerations
- Event name: up to 45 characters
- Event value: up to 1000 characters; if longer, it can be truncated
- Non-English characters are supported from iOS and Android versions 4.81.1 (or in-app events and other SDK API)
- Pricing and revenue:
- Only use numbers and decimals such as 5 or 5.2
- Up to 5 numbers after the decimal such as 5.12345
5.6 In-app purchase validation
See In-app purchase validation to learn more about this feature.
In-app purchase validation is available in the React Native plugin via validateAndLogInAppPurchase
.
6. Deep link with OneLink
Set up deep linking in two stages:
- Get conversion data in React Native.
- Set up the app to support deep linking.
6.1 Get conversion data to deep link in React Native
There are two methods to get conversion data:
- Deferred deep linking directs users to specific activities and customized content according to conversion data.
- Direct deep linking opens an app at a specific activity and the content can be customized according to conversion data.
Deferred deep linking: onInstallConversionData
To get conversion data, implement onInstallConversionData
. Code sample:
this.onInstallConversionDataCanceller = appsFlyer.onInstallConversionData(
(res) => {
if (JSON.parse(res.data.is_first_launch) == true) {
if (res.data.af_status === 'Non-organic') {
var media_source = res.data.media_source;
var campaign = res.data.campaign;
alert('This is first launch and a Non-Organic install. Media source: ' + media_source + ' Campaign: ' + campaign);
} else if (res.data.af_status === 'Organic') {
alert('This is first launch and a Organic Install');
}
} else {
alert('This is not first launch');
}
}
);
appsFlyer.initSdk(/*...*/);
Direct deep linking: onAppOpenAttribution
To get conversion data, implement onAppOpenAttribution
. Code sample:
this.onAppOpenAttributionCanceller = appsFlyer.onAppOpenAttribution((res) => {
console.log(res);
// implement logic to customize content
});
appsFlyer.initSdk(/*...*/);
7. Get conversion data
Access user attribution data for every new install:
- Done in real time and directly from the SDK.
- Give users personalized content.
- Send them to specific activities within an app to increase their engagement; see Deferred deep linking: onInstallConversionData.
Code samples:
import React, {Component} from 'react';
import {AppState, Platform, StyleSheet, Text, View, Button} from 'react-native';
import appsFlyer from 'react-native-appsflyer';
const options = {
devKey: "********",
isDebug: true,
onInstallConversionData : true
};
if (Platform.OS === 'ios') {
options.appId = "123456789";
}
this.onInstallConversionDataCanceller = appsFlyer.onInstallConversionData(
data => {
console.log("GCD");
console.log(data);
}
);
this.onAppOpenAttributionCanceller = appsFlyer.onAppOpenAttribution(
data => {
console.log("OAOA");
console.log(data);
}
);
appsFlyer.initSdk(options, (result) => {
console.log(result);
}, (error) => {
console.error(error);
}
);
type Props = {};
export default class App extends Component<Props> {
componentWillUnmount() {
// Optionaly remove listeners for deep link data if you no longer need them after componentWillUnmount
if (onInstallConversionDataCanceller) {
onInstallConversionDataCanceller();
console.log('unregister onInstallConversionDataCanceller');
onInstallConversionDataCanceller = null;
}
if (onAppOpenAttributionCanceller) {
onAppOpenAttributionCanceller();
console.log('unregister onAppOpenAttributionCanceller');
onAppOpenAttributionCanceller = null;
}
import React, {useEffect, useState} from 'react';
import {AppState, SafeAreaView, Text, View} from 'react-native';
import appsFlyer from 'react-native-appsflyer';
var onInstallConversionDataCanceller = appsFlyer.onInstallConversionData(
(res) => {
if (JSON.parse(res.data.is_first_launch) == true) {
if (res.data.af_status === 'Non-organic') {
var media_source = res.data.media_source;
var campaign = res.data.campaign;
console.log('This is first launch and a Non-Organic install. Media source: ' + media_source + ' Campaign: ' + campaign);
} else if (res.data.af_status === 'Organic') {
console.log('This is first launch and a Organic Install');
}
} else {
console.log('This is not first launch');
}
},
);
var onAppOpenAttributionCanceller = appsFlyer.onAppOpenAttribution((res) => {
console.log(res);
});
appsFlyer.initSdk(
{
devKey: 'K2a*********99',
isDebug: false,
appId: '41******5',
},
(result) => {
console.log(result);
},
(error) => {
console.error(error);
},
);
const Home = (props) => {
useEffect(() => {
return () => {
// Optionaly remove listeners for deep link data if you no longer need them after componentWillUnmount
if (onInstallConversionDataCanceller) {
onInstallConversionDataCanceller();
console.log('unregister onInstallConversionDataCanceller');
onInstallConversionDataCanceller = null;
}
if (onAppOpenAttributionCanceller) {
onAppOpenAttributionCanceller();
console.log('unregister onAppOpenAttributionCanceller');
onAppOpenAttributionCanceller = null;
}
};
});
return (
{'App'}
);
};
8. Attribution
Measure uninstalls
Measure the uninstall rate of users coming from different sources. This significant KPI helps you analyze and optimize your campaigns. Read about uninstall measurement instructions.
Two ways to set up uninstall measurement in Android:
- Set the Firebase server key in your app's settings in AppsFlyer.
- Get Firebase device token - Setting up uninstall measurement through React Native requires a Firebase device token. If done natively, the Firebase SDK provides this token. That's the not case in React Native. You need to integrate with 3rd party libraries for React Native that can give you a Firebase device token.
- Once you have the device token, pass it to the
updateServerUninstallToken
method:
appsFlyer.updateServerUninstallToken(newFirebaseToken, (success) => //... });
Two ways to set up uninstall measurement in iOS:
- Get device token. Setting up uninstall measurements depends on Apple push notifications, so your app needs to pass AppsFlyer the device token to register to APNS.
- Once you have the device token, pass it to the
updateServerUninstallToken
method:
appsFlyer.updateServerUninstallToken(deviceToken, (success) => { //... });
Set additional custom data
To integrate on the SDK level with external partner platforms (including Segment, Adobe, and Urban Airship), it is necessary to use the setAdditionalData
API.
Only use this API if the partner's integration article specifically states the setAdditionalData
API is needed.
appsFlyer.setAdditionalData(
{
val1: 'data1',
val2: false,
val3: 23,
},
(res) => {
//...
}
);
9. Sessions
Custom time between sessions
Background sessions for utility apps
Not available in the React Native plugin. See instructions for Android.
10. Owned media
Resolve wrapped deep-link URLs
Record push notifications
User invite attribution
If you allow existing app users to invite their friends and contacts to become new users, this can be a key growth factor for your app.
With AppsFlyer, you can attribute and record installs that originate from user invites within your app.
There are two steps:
- Set OneLink ID.
- Generate invite link.
Set OneLink ID
setAppInviteOneLinkID(oneLinkID, callback)
Generate invite link
appsFlyer.generateInviteLink(
{
channel: 'gmail',
campaign: 'myCampaign',
customerID: '1234',
userParams: {
myParam: 'newUser',
anotherParam: 'fromWeb',
amount: 1,
},
},
(link) => {
console.log(link);
},
(err) => {
console.log(err);
}
);
11. User identifiers
Get AppsFlyer ID
An AppsFlyer ID is created for every new install of an app. You can use the AppsFlyer ID for various purposes:
- Send server-to-server in-app events.
- Match the AppsFlyer ID with user records in your back-end systems.
- Map entries when merging data from pull and push API.
Use this API to obtain a unique AppsFlyer ID:
appsFlyer.getAppsFlyerUID((err, appsFlyerUID) => {
if (err) {
console.error(err);
} else {
console.log('on getAppsFlyerUID: ' + appsFlyerUID);
}
});
Set customer user ID
Set your own unique customer user ID (CUID) and cross-reference it with a unique AppsFlyer ID.
Unique CUID:
- Appear in AppsFlyer raw data CSV reports.
- Can be used in postback APIs to cross-reference with internal IDs.
To set your CUID, use:
appsFlyer.setCustomerUserId('some_user_id', (res) => {
//..
});
Recommended practice! Set the CUID early in the app flow—it is only associated with events reported after its setup.
Call setCustomerUserId
before calling trackAppLaunch
- Recorded events will be associated with the CUID.
- Related data will appear in the raw data reports for installs and events.
- If set later, then the CUID will only be associated with events recorded after setting the CUID.
12. User privacy
Opt-out
Different scenarios, such as legal and privacy compliance issues, may lead to a decision to opt-out and stop all SDK tracking. Best practice! Follow the exact instructions for the scenario relevant to your app.
To stop tracking:
- Call isStopTracking and set to true.
stopTracking(isStopTracking, callback)
- SDK stops functioning and no longer communicates with AppsFlyer servers.
To reactivate tracking: Call isStopTrackingIn and set to false.
Anonymize user data
Exclude partners from getting data
In some cases, advertisers may want to stop sharing user-level data with ad networks/partners for specific users. Reasons for this include:
- Privacy policies such as CCPA or GDPR
- User opt-out mechanisms
- Competition with some partners (ad networks, 3rd parties)
AppsFlyer provides two API methods to stop sharing data with some or all partners:
- setSharingFilter: Used by advertisers to prevent sharing data with some (one or more) networks/integrated partners.
- setSharingFilterForAllPartners: Used by advertisers to prevent sharing data with all networks/integrated partners.
These filtering methods are supported as of SDK V5.4.1.
The filtering method must be called every time the SDK is initialized and affects the whole session. If it takes time to determine whether you need to set the sharing filters, then delay the SDK initialization.
When the method is activated before the first trackAppLaunch call:
- Users from SRNs are attributed as Organic, and their data is not shared with integrated partners.
- Users from click ad networks (non-SRNs) are attributed correctly in AppsFlyer, but not shared with the ad networks via postbacks, APIs, raw data reports, or by any other method.
Currently, uninstall data can't be filtered using these methods. However, you can stop sending Uninstall events to partners using their setup pages in AppsFlyer.
initSDK
Description |
Initialize the AppsFlyer SDK with the dev key and app ID. The dev key is required for all apps, while the app ID is required only for iOS. (You can pass the app ID on Android as well, and it will be ignored. |
Method signature |
|
Example |
|
trackAppLaunch
Description |
Two functions:
|
Method signature |
|
Example |
|
onInstallConversionData
Description |
Allows access of AppsFlyer attribution/conversion data from the SDK (deferred deep linking). The code implementation for the conversion listener must be made prior to the initialization code of the SDK. |
Method signature |
|
Example |
|
onAppOpenAttribution
Description |
Get deep link data when the app opens via a deep link. |
Method signature |
|
Example |
|
logEvent
Description |
Sends in-app events to AppsFlyer. See recording in-app events. |
Method signature |
|
Example |
|
setCustomerUserId
Description |
Sets the Customer User ID (CUID). See setting the Customer User ID. |
Method signature |
|
Example |
|
getAppsFlyerUID
Description |
Get the AppsFlyer ID. For more information see here. |
Method signature |
|
Example |
|
stopTracking
Description |
Stop all SDK functionality. See user privacy (opt-out). |
Method signature |
|
Example |
|
trackLocation
Description |
Manually record the location of the user. |
Method signature |
|
Example |
|
setUserEmails
Description |
Set and encrypt user emails. |
Method signature |
|
Example |
|
setAdditionalData
Description |
Adds additional data to be sent to external partner platforms. |
Method signature |
|
Example |
|
updateServerUninstallToken - Android only
Description |
Manually pass the Firebase/GCM device token for uninstall measurement. |
Method signature |
|
Example |
|
setCollectIMEI - Android only
Description |
Indicates if the IMEI should be sent to AppsFlyer. |
Method signature |
|
Example |
|
setCollectAndroidID - Android only
Description |
Indicates if the Android ID should be sent to AppsFlyer. |
Method signature |
|
Example |
|
setAppInviteOneLinkID
Description |
Set the OneLink template ID for creating custom attribution links for user invites. Used together with generateInviteLink. |
Method signature |
|
Example |
|
generateInviteLink
Description |
Set the OneLink ID before calling this method. The link generator builds the invite URL.
|
Method signature |
|
Example |
|
trackCrossPromotionImpression
Description |
Used to attribute an impression use the following API call. Make sure to use the promoted app ID as it displays within the AppsFlyer dashboard. |
Method signature |
|
Example |
|
trackAndOpenStore
Description |
Used to attribute the click and launch the app store's app page. |
Method signature |
|
Example |
|
setCurrencyCode
Description |
Sets the currency code for all events.
|
Method signature |
|
Example |
|
setDeviceTrackingDisabled
Description |
Used to anonymize specific user identifiers within AppsFlyer analytics. This complies with both the latest privacy requirements (GDPR, COPPA) and Facebook's data and privacy policies. |
Method signature |
|
Example |
|
setOneLinkCustomDomains
Description |
Used during the SDK initialization to indicate set OneLink custom links/branded domains. Learn more about Branded Links. |
Method signature |
|
Example |
|
setResolveDeepLinkURLs
Description |
Used during the SDK initialization to indicate that links from certain domains (domains used by ESP when wrapping your deep links) should be resolved in order to get the original deep link. Learn more. |
Method signature |
|
Example |
|
performOnAppAttribution
Description |
This function allows developers to manually re-trigger onAppOpenAttribution with a specific link (URI or URL), without recording a new re-engagement. |
Method signature |
|
Example |
|
setSharingFilterForAllPartners
Description |
Used by advertisers to exclude all networks/integrated partners from getting data. Learn more. |
Method signature |
|
Example |
|
setSharingFilter
Description |
Used by advertisers to set some (one or more) networks/integrated partners to exclude from getting data. Learn more. |
Method signature |
|
Example |
|