React Native SDK Reference
Complete API reference for the PushEngage React Native SDK. For setup and installation, see the React Native Quickstart.
The SDK supports React Native 0.78+ with turbo module support. It uses FCM for Android and APNs for iOS.
This bridge pins PushEngage iOS native SDK 1.0.0 (the two-module PushEngage + PushEngageExtension split) and PushEngage Android native SDK 0.1.0.
Initialization
setAppId
Call this method in your root index.js before AppRegistry.registerComponent to set the app push ID in the SDK, registering the subscriber to that specific app push ID. The app push ID can be obtained from your PushEngage Dashboard Settings.
For more information, see the PushEngage React Native Reference.
This method must be called before using any other SDK features. It associates all subsequent operations with your specific PushEngage application.
Syntax
setAppId: (appId: string) => void
Parameters
appId: A String representing the app push ID to be set.
- This ID uniquely identifies the app in the push notification service.
- Must be a valid app push ID provided by PushEngage.
Usage
PushEngage.setAppId('YOUR_APP_PUSH_ID');
- Call this method early in your app's lifecycle, typically in your root component
setEnvironment
Switch the SDK between the PRODUCTION and STAGING backends. This is intended for internal testing against the PushEngage staging environment — most apps should leave the default (production) untouched.
setAppIdsetEnvironment must be invoked before setAppId. Switching the environment after initialization is unsupported and may leave the subscriber registered against the previous environment.
Syntax
setEnvironment: (environment: 'STAGING' | 'PRODUCTION') => void
The Environment type is also exported for re-use:
import PushEngage, {
type Environment,
} from '@pushengage/pushengage-react-native';
const env: Environment = 'PRODUCTION';
Parameters
environment: 'STAGING' or 'PRODUCTION'.
Usage
PushEngage.setEnvironment('PRODUCTION');
PushEngage.setAppId('YOUR_APP_PUSH_ID');
enableLogging
Enable or disable logging for the PushEngage SDK.
Syntax
enableLogging: (shouldEnable: boolean) => void
Parameters
shouldEnable: Boolean indicating whether logging should be enabled (true) or disabled (false).
Usage
// Enable logging
PushEngage.enableLogging(true);
// Disable logging
PushEngage.enableLogging(false);
Notification Permission
requestNotificationPermission
The requestNotificationPermission method handles the crucial step of obtaining user consent for push notifications. This method presents the system permission prompt to the user and manages their response.
Without the necessary permissions, your app cannot deliver push notifications to the user. This function is crucial as it ensures that the user grants permission for notifications, allowing the app to deliver timely and relevant updates. If the user denies permission, the app will not be able to receive notifications.
Syntax
requestNotificationPermission: () => Promise<boolean>;
Returns
Promise resolving to:
true: Permission granted
false: Permission denied/rejected
Usage
const isGranted: boolean = await PushEngage.requestNotificationPermission();
Common Use Cases
- First time app-launch
// In your onboarding flow
async function onboardingComplete() {
const hasPermission = await PushEngage.requestNotificationPermission();
if (hasPermission) {
// Add your code implementation here
}
}
- Feature-specific permission
// When enabling a feature that needs notifications
async function enableDeliveryUpdates() {
const hasPermission = await PushEngage.requestNotificationPermission();
if (hasPermission) {
// Add your code implementation here
}
}
Request permission at an appropriate time in the user journey
Explain the benefits of push notifications before requesting
getNotificationPermissionStatus
Get the current notification permission status for the application.
Syntax
getNotificationPermissionStatus: () => string;
Returns
A string indicating the current notification permission state:
"granted": The application is authorized to post user notifications"denied": The application is not authorized to post user notifications"notYetRequested": (iOS only) The user has not yet made a choice regarding notification permissions
Usage
function checkPermissionStatus() {
const permissionStatus = PushEngage.getNotificationPermissionStatus();
switch (permissionStatus) {
case 'granted':
console.log('Notifications are allowed');
break;
case 'denied':
console.log('Notifications are denied');
break;
case 'notYetRequested':
console.log('Permission not yet requested'); // iOS only
break;
default:
console.log('Unknown permission status');
break;
}
}
Subscription
subscribe
Subscribe the user to push notifications. This method checks the current permission status and subscription state to determine the appropriate action.
Syntax
subscribe: () => Promise<void>;
Returns
Promise that resolves when subscribe operation completes successfully, or throws an error if the operation fails.
Usage
async function subscribeUser() {
try {
await PushEngage.subscribe();
console.log('User subscribed successfully');
} catch (error) {
console.error('Failed to subscribe user:', error);
}
}
unsubscribe
Unsubscribe the user from push notifications while preserving their subscription record. The user can be re-subscribed later using the subscribe() method.
Syntax
unsubscribe: () => Promise<void>;
Returns
Promise that resolves when unsubscribe operation completes successfully, or throws an error if the operation fails.
Usage
async function unsubscribeUser() {
try {
await PushEngage.unsubscribe();
console.log('User unsubscribed successfully');
} catch (error) {
console.error('Failed to unsubscribe user:', error);
}
}
getSubscriptionStatus
Check whether the user is currently subscribed to push notifications.
Syntax
getSubscriptionStatus: () => Promise<boolean>;
Returns
Promise resolving to:
true: User is subscribed to push notificationsfalse: User is not subscribed (unsubscribed or never subscribed)
Usage
async function checkSubscriptionStatus() {
try {
const isSubscribed = await PushEngage.getSubscriptionStatus();
if (isSubscribed) {
console.log('User is subscribed to push notifications');
} else {
console.log('User is not subscribed to push notifications');
}
} catch (error) {
console.error('Error checking subscription status:', error);
}
}
getSubscriptionNotificationStatus
Check whether the user can actually receive push notifications by verifying both subscription status and notification permission. The user can receive notifications only if they are subscribed AND the app has notification permission granted.
Syntax
getSubscriptionNotificationStatus: () => Promise<boolean>;
Returns
Promise resolving to:
true: User can receive notifications (subscribed AND permission granted)false: User cannot receive notifications (not subscribed or permission denied)
Usage
async function checkNotificationCapability() {
try {
const canReceiveNotifications =
await PushEngage.getSubscriptionNotificationStatus();
if (canReceiveNotifications) {
console.log('User can receive push notifications');
} else {
console.log('User cannot receive push notifications');
}
} catch (error) {
console.error('Error checking notification capability:', error);
}
}
Associate Profile ID
Profile IDs serve as unique identifiers for your subscribers, enabling you to recognize them across multiple devices. Each subscriber can be assigned just one profile ID. This ID should be a string, and you have the flexibility to use any value, such as an email or phone number.
getSubscriberId
Retrieve the unique subscriber ID for a user. PushEngage generates this ID for every user based on their subscription data. Sometimes, this ID is referred to as the 'subscriber_hash'. The subscriber ID remains consistent unless there's a change in the user's subscription.
Syntax
getSubscriberId: () => Promise<string | null>;
Returns
Promise resolving to:
string: The subscriber ID if the user is subscribednull: If the user is not subscribed
Usage
async function getSubscriberId() {
try {
const subscriberId = await PushEngage.getSubscriberId();
if (subscriberId) {
console.log('Subscriber ID:', subscriberId);
return subscriberId;
} else {
console.log('User is not subscribed or no valid ID available');
return null;
}
} catch (error) {
console.error('Error getting subscriber ID:', error);
return null;
}
}
addProfileId
This method allows you to set a profile ID for the current subscriber. If a profile ID already exists, it will be replaced with the new value.
Syntax
addProfileId: (profileId: string) => Promise<string | null>;
Parameters
profileId: Unique identifier for the subscriber
Returns
Promise resolving to:
string: A success message.
The promise rejects with an error (code and message) if the operation fails.
Usage
async function setProfileId() {
try {
const profileId = '[email protected]';
const result = await PushEngage.addProfileId(profileId);
if (result) {
console.log('Profile ID set successfully:', result);
}
} catch (error) {
console.error('Failed to set profile ID:', error);
}
}
Common use cases
- Cross-device user identification
- Integration with CRM systems
User Identity
The identify and logout methods manage the predefined personal-data fields stored on the current subscriber. Use them to tie a push subscription to your own first-party user data and to clear that data on sign-out without unsubscribing the device.
The 12 valid keys are: first_name, last_name, email, phone, gender, dob, language, profile_id, country, city, state, zip. Values must be string, number, or boolean — other types are rejected by the native layer.
identify
Upsert one or more of the 12 predefined subscriber fields. Repeat calls with the same payload short-circuit locally and resolve without a network round-trip; the local cache has a 24h TTL so dashboard-side edits surface within a day. Numeric profile_id values are coerced to their string form before being sent.
Syntax
identify: (fields: IdentifyFields) => Promise<void>;
The IdentifyFields type is exported for re-use:
import PushEngage, {
type IdentifyFields,
} from '@pushengage/pushengage-react-native';
Parameters
fields: An object containing one or more of the 12 valid subscriber fields. Undefined keys are stripped before the call. At least one defined key is required.
| Key | Type | Description |
|---|---|---|
first_name | string | number | boolean | Subscriber's first name |
last_name | string | number | boolean | Subscriber's last name |
email | string | number | boolean | Email address |
phone | string | number | boolean | Phone number |
gender | string | number | boolean | Gender |
dob | string | number | boolean | Date of birth |
language | string | number | boolean | Locale/language code |
profile_id | string | number | boolean | Your own user ID; numeric values are auto-coerced to string |
country | string | number | boolean | Country |
city | string | number | boolean | City |
state | string | number | boolean | State / region |
zip | string | number | boolean | Postal code |
Usage
async function setSubscriberFields() {
try {
await PushEngage.identify({
first_name: 'Jane',
last_name: 'Doe',
email: '[email protected]',
profile_id: 'user_12345',
});
console.log('Subscriber fields updated');
} catch (error) {
console.error('Identify failed:', error);
}
}
logout
Remove a set of predefined personal fields from the current subscriber while keeping the device subscribed for push. Call this when a user signs out of your app to detach their PII from the push subscription.
Passing null or an empty array removes the default PII field set: first_name, last_name, email, phone, gender, dob, profile_id. Passing a non-empty array of field names scopes the removal to those specific fields. If none of the requested field names are currently cached locally (and the cache is fresh — within 24 hours of the last successful sync), the call resolves without a network request.
Syntax
logout: (fieldNames: string[] | null) => Promise<void>;
Parameters
fieldNames: An array of field names to remove, or null (or an empty array) to clear the default PII set.
The wrapper rejects with a TypeError at the JS boundary when fieldNames is an array containing a non-string element.
Usage
// Clear the default PII set
await PushEngage.logout(null);
// Clear specific fields
await PushEngage.logout(['email', 'phone']);
Custom Events
trackEvent
Track a custom event for the current subscriber. Custom events are used to start or exit campaign workflows based on in-app activity — for example, adding an item to cart, completing a purchase, or any other action you define. Workflows are configured from the PushEngage Dashboard.
Syntax
trackEvent: (event: TrackEventPayload) => Promise<void>;
The TrackEventPayload type is exported for re-use:
import PushEngage, {
type TrackEventPayload,
} from '@pushengage/pushengage-react-native';
Parameters
event: A TrackEventPayload object describing the event.
| Field | Type | Required | Description |
|---|---|---|---|
eventName | string | Yes | Name of the event (e.g., "MySite.AddToCart"). |
data | object | No | Custom key-value data. Values must be string, number, or boolean. |
profileId | string | No | Profile ID of the subscriber. |
provider | string | No | Provider name. Defaults to "PushEngage". |
eventType | string | No | Event type. Defaults to "PushEngage.CustomEvent". |
Usage
async function trackAddToCart() {
try {
await PushEngage.trackEvent({
eventName: 'MySite.AddToCart',
data: {
product_id: '123',
product_name: 'Product Name',
price: 49.99,
},
});
console.log('Event tracked');
} catch (error) {
console.error('Failed to track event:', error);
}
}
Subscriber Details
getSubscriberDetails
This method retrieves subscriber details based on a provided list of strings, which can include city, state, country, device, device type, segments, etc.
Syntax
getSubscriberDetails: (values: string[] | null) =>
Promise<{ [key: string]: string | number | boolean } | null>;
Parameters
values: A list of strings that can contain any values from above mentioned fields.
- Specify which subscriber details you want to retrieve.
- Can include fields like city, state, country, device type, segments, etc.
Returns
Promise resolving to:
{ [key: string]: string | number | boolean }: Object containing subscriber detailsnull: If no details are available (the promise rejects if the lookup fails)
Usage
async function fetchSubscriberDetails() {
try {
const subscriberAttributes = [
'city',
'device',
'host',
'user_agent',
'has_unsubscribed',
'device_type',
'timezone',
'country',
'ts_created',
'state',
];
const details = await PushEngage.getSubscriberDetails(subscriberAttributes);
if (details) {
console.log('City:', details.city);
console.log('Device:', details.device);
console.log('Country:', details.country);
}
} catch (error) {
console.error('Failed to get subscriber details:', error);
}
}
Available Fields
| Field | Type | Description |
|---|---|---|
city | string | Subscriber's city |
state | string | Subscriber's state or region |
country | string | Subscriber's country |
device | string | Device name |
device_type | string | Device type (e.g., mobile, tablet) |
user_agent | string | App user agent string |
host | string | Host identifier |
timezone | string | Subscriber's timezone |
has_unsubscribed | boolean | Whether the subscriber has unsubscribed |
ts_created | string | ISO 8601 timestamp of subscription creation |
segments | array | Segment IDs the subscriber belongs to |
Segments
Segments are used to group subscribers so that you can send personalized notifications. Segments can be created based on attributes, categories, and more. Each subscriber can belong to up to 50 segments.
Where to create
You can create and manage segments in the PushEngage Dashboard or using the rest APIs. The dashboard provides an intuitive interface to set up various types of campaigns, define triggers, and customize the notification content.
- Log in to your PushEngage Dashboard.
- Navigate to the Audience section.
- Select Segments and click Create a New Segment.
- Define the segment name and criteria and save it.
addSegment
This method enables you to add the current subscriber to segments.
Syntax
addSegment: (segments: string[]) => Promise<string | null>;
Parameters
segments: A list of segments to be added.
Returns
Promise resolving to:
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function addToSegments() {
try {
const segments = ['premium_users', 'active_30d', 'mobile_app'];
const result = await PushEngage.addSegment(segments);
if (result) {
console.log('Segments added:', result);
} else {
console.log('Failed to add segments');
}
} catch (error) {
console.error('Error adding segments:', error);
}
}
addDynamicSegment
This method enables you to add the current subscriber to a segment for a specified duration, measured in days. After this period, the segment will be automatically removed from the subscriber.
Syntax
addDynamicSegment: (segments: { name: string; duration: number }[]) =>
Promise<string | null>;
Parameters
segments: A list of segment objects representing dynamic segments to be added.
Returns
Promise resolving to:
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function addDynamicSegments() {
try {
const segments = [
{ name: 'trial_users', duration: 30 },
{ name: 'new_customers', duration: 90 },
];
const result = await PushEngage.addDynamicSegment(segments);
if (result) {
console.log('Dynamic segments added:', result);
} else {
console.log('Failed to add dynamic segments');
}
} catch (error) {
console.error('Error adding dynamic segments:', error);
}
}
removeSegment
This method allows you to remove the current subscriber from segments.
Syntax
removeSegment: (segments: string[]) => Promise<string | null>;
Parameters
segments: The list of segment to be removed.
Returns
Promise resolving to:
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function removeFromSegments() {
try {
const segments = ['segment1', 'segment2', 'segment3'];
const result = await PushEngage.removeSegment(segments);
if (result) {
console.log('Segments removed:', result);
} else {
console.log('Failed to remove segments');
}
} catch (error) {
console.error('Error removing segments:', error);
}
}
Attributes
Attributes are key-value pairs that allow you to store additional information about your subscribers. You can utilize attributes to segment your subscribers and send personalized notifications. Each subscriber can have a maximum of 50 attributes. The key of an attribute can be up to 64 characters long, and the value can be up to 128 characters long in the case of a string.
You first need to create attributes before using them. You can create them from the PushEngage Dashboard.
addSubscriberAttributes
Use this method to add or update attributes for a subscriber. If an attribute with the specified key already exists, the existing value will be replaced.
Syntax
addSubscriberAttributes: (attributes: { [key: string]: string }) =>
Promise<string | null>;
Parameters
attributes: Object containing key-value pairs of attributes.
Returns
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function addAttributes() {
try {
const attributes = {
age: '25',
height: '6.1',
plan: 'premium',
};
const result = await PushEngage.addSubscriberAttributes(attributes);
if (result) {
console.log('Attributes added:', result);
} else {
console.log('Failed to add attributes');
}
} catch (error) {
console.error('Error adding attributes:', error);
}
}
setSubscriberAttributes
This method allows you to set attributes for a subscriber, replacing any previously associated attributes. Use this method when you need to entirely reset the attributes with new values.
Syntax
setSubscriberAttributes: (attributes: { [key: string]: string }) =>
Promise<string | null>;
Parameters
attributes: Object containing key-value pairs of attributes to set.
Returns
Promise resolving to:
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function setAttributes() {
try {
const attributes = {
age: '30',
height: '5.9',
plan: 'basic',
};
const result = await PushEngage.setSubscriberAttributes(attributes);
if (result) {
console.log('Attributes set:', result);
} else {
console.log('Failed to set attributes');
}
} catch (error) {
console.error('Error setting attributes:', error);
}
}
getSubscriberAttributes
Retrieve the attributes associated with the current subscriber using this method.
Syntax
getSubscriberAttributes: () =>
Promise<{ [key: string]: string | number | boolean } | null>;
Returns
Promise resolving to:
{ [key: string]: string | number | boolean }: Object containing subscriber attributes
null: If no attributes are set (the promise rejects if the lookup fails)
Usage
async function getSubscriberAttributes() {
try {
const attributes = await PushEngage.getSubscriberAttributes();
if (attributes) {
console.log('Subscriber attributes:', attributes);
} else {
console.log('No attributes found');
}
} catch (error) {
console.error('Error fetching attributes:', error);
}
}
deleteSubscriberAttributes
This method allows you to remove one or more attributes from the current subscriber. Provide an array of attribute names you wish to remove. Passing an empty array will result in the removal of all the subscriber's attributes.
Syntax
deleteSubscriberAttributes: (attributes: string[]) => Promise<string | null>;
Parameters
attributes: Array of attribute names to delete.
Returns
Promise resolving to:
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function removeAttributes() {
try {
const attributes = ['age', 'height'];
const result = await PushEngage.deleteSubscriberAttributes(attributes);
if (result) {
console.log('Attributes deleted:', result);
} else {
console.log('Failed to delete attributes');
}
} catch (error) {
console.error('Error deleting attributes:', error);
}
}
Automated Notifications
Automated notifications include all types of triggered campaigns, such as cart abandonment, price drop, back in stock, and browse abandonment. By default, automated notifications are enabled for all subscribers.
automatedNotification
This method allows you to enable/disable automated notifications for the current subscriber.
Syntax
automatedNotification: (status: boolean) => Promise<string | null>;
Parameters
status: true to enable the trigger campaign for this subscriber, false to disable it.
Returns
Promise resolving to:
string:
Success: Confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
Enable Automated Notifications
await PushEngage.automatedNotification(true);
Disable Automated Notifications
await PushEngage.automatedNotification(false);
For a reusable pattern:
async function toggleAutomatedNotifications(enable: boolean) {
try {
const result = await PushEngage.automatedNotification(enable);
if (result) {
console.log('Automated notifications updated:', result);
}
} catch (error) {
console.error('Error updating automated notifications:', error);
}
}
Triggered Campaigns
Triggered campaigns are predefined notifications that are automatically sent to users when they perform certain actions or meet specific conditions. For example, a Custom Trigger Campaign detects your visitor's behavior to send automated push notifications to the right person at the right time. Browse Abandonment campaigns send targeted messages to convert visitors who viewed certain pages, such as product pages or feature pages. Cart Abandonment campaigns help recover lost sales and quickly boost revenue with automatically triggered abandon cart push notifications. Price Drop campaigns re-engage your customers and increase conversion using Price Drop Alert Campaigns. Back in Stock Alert campaigns re-engage your customers and increase conversion using Inventory Alert Campaigns.
sendTriggerEvent
Detect your user's behavior to send automated push notifications to the right person at the right time.
Where to Create
You can create and manage triggered campaigns in the PushEngage Dashboard. The dashboard provides an intuitive interface to set up various types of campaigns, define triggers, and customize the notification content.
- Log in to your PushEngage Dashboard.
- Navigate to the Campaign section.
- Select Triggered Campaigns and click Create New Triggered Campaign.
- Select from either of the following options:
- Custom Trigger Campaign
- Browse Abandonment
- Cart Abandonment
- Define the trigger conditions and customize the notification content.
Syntax
sendTriggerEvent: (trigger: {
[key: string]: string | Record<string, string>;
}) => Promise<string | null>;
Parameters
trigger: The TriggerCampaign object representing the campaign event to be triggered.
Returns
Promise resolving to:
string:
Success: Trigger confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
async function triggerCampaign() {
try {
const trigger = {
campaignName: 'Welcome',
eventName: 'user_signup',
referenceId: '12345',
data: {
plan: 'premium',
source: 'mobile',
},
};
const result = await PushEngage.sendTriggerEvent(trigger);
if (result) {
console.log('Trigger campaign result:', result);
}
} catch (error) {
console.error('Failed to trigger campaign:', error);
}
}
campaignName and eventName can be found in the PushEngage Dashboard for the respective trigger campaign.
addAlert
Re-engage your customers and increase conversion using Price Drop Alert Campaigns and Inventory Alert Campaigns.
Where to Create
You can create and manage triggered alerts in the PushEngage Dashboard. The dashboard provides an intuitive interface to set up various types of campaigns, define triggers, and customize the notification content.
- Log in to your PushEngage Dashboard.
- Navigate to the Campaign section.
- Select Triggered Campaigns and click Create New Triggered Campaign.
- Select from either of the following options:
- Price Drop
- Back in Stock Alert
- Define the trigger conditions and customize the notification content.
Syntax
addAlert: (alert: { [key: string]: string | number | undefined }) =>
Promise<string | null>;
Parameters
alert: The TriggerAlert object representing the alert to be added.
Returns
Promise resolving to:
string:
Success: Alert confirmation message
The promise rejects with an error (code and message) if the operation fails.
Usage
Price Drop
async function addPriceDropAlert() {
try {
const alert = {
type: 'priceDrop',
productId: 'prod_123',
link: 'https://example.com/product/123',
price: 99.99,
alertPrice: 89.99, // Optional: target price for alert; omitted when unset (server may apply a default)
};
const result = await PushEngage.addAlert(alert);
if (result) {
console.log('Price drop alert added:', result);
}
} catch (error) {
console.error('Failed to add alert:', error);
}
}
Back in Stock Alert
async function addInventoryAlert() {
try {
const alert = {
type: 'inventory',
productId: 'prod_123',
link: 'https://shop.com/product/123',
price: 99.99,
};
const result = await PushEngage.addAlert(alert);
if (result) {
console.log('Inventory alert added:', result);
}
} catch (error) {
console.error('Failed to add alert:', error);
}
}
Goal Tracking
Goal Tracking will help you assign conversion goals & value to your notification campaigns. You can set up a default goal and have it integrated for all your campaigns.
sendGoal
Where to Enable
You can enable/disable goal tracking in the PushEngage Dashboard. The dashboard provides an intuitive interface to set up tracking method, tracking duration, goal name and currency.
- Log in to your PushEngage Dashboard.
- Navigate to the Analytics section.
- Select Goal Tracking and tick Enable Goal Tracking.
Syntax
sendGoal: (goal: { [key: string]: string | number }) => Promise<string | null>;
Parameters
goal: Goal object representing the goal to be tracked.
Returns
Promise resolving to:
string:
Success: Goal tracking confirmation
The promise rejects with an error (code and message) if the operation fails.
Usage
async function sendGoal() {
try {
const goal = {
name: 'revenue',
count: 1,
value: 10,
};
const result = await PushEngage.sendGoal(goal);
if (result) {
console.log('Goal tracked:', result);
} else {
console.log('Failed to track goal');
}
} catch (error) {
console.error('Error tracking goal:', error);
}
}
name can be found in the PushEngage Dashboard under the Goal Tracking section.
Deep Linking
onValueChanged
Listen for deep link events and handle them in your application. A deep link can be a custom URL scheme or a standard HTTPS/HTTP URL. Tapping these links routes users directly to the desired content.
The deep linking functionality allows you to:
- Handle custom URL schemes
- Process universal links (HTTP/HTTPS URLs)
- Navigate users to specific screens based on notification interactions
- Pass custom data through notifications
Syntax
readonly onValueChanged: EventEmitter<{
deepLink: string;
data: { [key: string]: string };
}>
Returns
type DeepLinkData = {
deepLink: string; // The deep link URL/string
data: Record<string, string>; // Additional data payload
};
Usage
import { type EventSubscription } from 'react-native';
const listenerSubscription = React.useRef<null | EventSubscription>(null);
React.useEffect(() => {
listenerSubscription.current = PushEngage.onValueChanged((data) => {
console.log('Deep link:', data.deepLink);
console.log('Data:', data.data);
});
return () => {
listenerSubscription.current?.remove();
listenerSubscription.current = null;
};
}, []);
Common use cases
- E-commerce apps: Linking directly to product pages or carts.
- Content platforms: Linking to specific articles or videos.
- Social apps: Linking directly to user profiles or posts.
Implement fallback behavior for invalid deep links
Test deep links across different app states (foreground, background, terminated)
getInitialNotification
Recover the deep link from a notification tap that launched the app from a terminated (cold-boot) state. On iOS, onValueChanged only fires for taps that happen after the JS subscriber is attached, so the first cold-boot tap is lost. getInitialNotification is the pull-based companion — call it once during startup, in addition to subscribing via onValueChanged, and the SDK delivers the buffered cold-boot tap (if any).
This method returns null on Android. Cold-boot deep links on Android flow through the host activity's intent filter and are not buffered by the SDK.
Syntax
getInitialNotification: () => Promise<InitialNotification | null>;
The InitialNotification type is exported for re-use:
import PushEngage, {
type InitialNotification,
} from '@pushengage/pushengage-react-native';
Returns
Promise resolving to:
InitialNotificationobject — the deep link from the cold-boot notification tap, when one was buffered:{
deepLink: string;
data: { [key: string]: string };
}null— when there was no cold-boot tap to recover (warm-boot launches, app already running, repeated calls after the buffered value was consumed, or Android).
The buffered value is consumed by the first successful call; subsequent calls resolve null.
Usage
React.useEffect(() => {
PushEngage.getInitialNotification().then((initial) => {
if (initial) {
console.log('Cold-boot deep link:', initial.deepLink);
// Navigate based on initial.deepLink / initial.data
}
});
}, []);
Utilities
getSdkVersion
Retrieves the current version of the PushEngage React Native SDK, returning a string that represents the SDK's current version.
Syntax
getSdkVersion: () => string;
Returns
A String representing the current version of the PushEngage React Native SDK.
Usage
PushEngage.getSdkVersion();
setSmallIconResource
Sets the resource name of the small icon used for notifications. The small icon appears in the status bar when a notification is displayed.
Only Android applies the resource name to outgoing notifications. On iOS the call is a no-op — the promise resolves with no value.
Syntax
setSmallIconResource: (resourceName: string) => Promise<void>;
Parameters
resourceName: A string representing the resource name of the small icon.
Usage
async function setNotificationIcon() {
if (Platform.OS === 'android') {
try {
await PushEngage.setSmallIconResource('your_icon_name');
console.log('Small icon set');
} catch (error) {
console.error('Failed to set small icon:', error);
}
}
}
It is recommended to set a valid resource name to ensure proper display of notifications. If an invalid resource name is provided, the default bell icon specified by the PushEngage library will be used.
setBadgeCount
Set the badge count for the application icon. The call is fire-and-forget — it dispatches to native and returns immediately without a result.
- iOS: Sets the launcher icon badge directly. Uses
UNUserNotificationCenter.setBadgeCounton iOS 16+, withapplicationIconBadgeNumberfallback on older versions. - Android: Stores the value and applies it to notifications the SDK builds afterwards. Android has no system API for a numeric launcher-icon badge — the count surfaces in the long-press shortcut menu. Passing
0additionally clears all active notifications (viaNotificationManagerCompat.cancelAll()), dismissing the app's entire notification tray.
Invalid input (NaN, ±Infinity, or values outside the native Int range) is coerced to 0 (badge cleared).
Syntax
setBadgeCount: (count: number) => void;
Parameters
count: The badge count. Pass 0 to clear the badge.
Usage
// Set the badge to 5
PushEngage.setBadgeCount(5);
// Clear the badge
PushEngage.setBadgeCount(0);
Diagnostics (Android)
The methods in this section are Android-only — they help diagnose Firebase Cloud Messaging configuration drift between your google-services.json and the configuration registered on the PushEngage dashboard. iOS calls resolve as no-ops so cross-platform code can call them unconditionally.
runConfigValidation
Re-run the SDK's FCM configuration validator and asynchronously emit any mismatches via onFcmConfigError. Useful as a one-shot check during integration to surface sender-ID or project-ID drift early. iOS resolves true as a no-op.
Syntax
runConfigValidation: (senderId: string, projectId: string) => Promise<boolean>;
Parameters
senderId: The Firebase sender ID expected by your PushEngage site.
projectId: The Firebase project ID expected by your PushEngage site.
Returns
Promise resolving to:
true— the configuration matches, the check was skipped (Firebase not yet initialized), or the call was a no-op on iOS.false— a mismatch was detected (sender ID, project ID, or both).
The specific mismatch details are also delivered asynchronously through onFcmConfigError. If the validator itself throws, the promise rejects with CONFIG_VALIDATION_ERROR — it never resolves false to signal "could not run".
Usage
const ok = await PushEngage.runConfigValidation(
'1234567890',
'my-firebase-project',
);
console.log('Config validation dispatched:', ok);
onFcmConfigError
Subscribe to Firebase Cloud Messaging configuration errors emitted by the Android native SDK. Common causes are sender-ID or project-ID mismatches between google-services.json and the PushEngage dashboard. Native forwarding is enabled automatically on module load — subscribe via PushEngage.onFcmConfigError(callback) and remove the subscription with subscription.remove().
The Android error codes are:
| Code | Meaning |
|---|---|
5001 | FCM_SENDER_ID_MISMATCH — google-services.json sender ID does not match the dashboard. |
5002 | FCM_PROJECT_ID_MISMATCH — google-services.json project ID does not match the service-account JSON. |
5003 | FCM_LOCAL_CONFIG_INVALID — Firebase Installations rejected google-services.json as invalid for the app. |
5004 | FCM_CONFIG_BOTH_MISMATCH — both sender ID and project ID differ from the dashboard configuration. |
The native iOS bridge does not emit FCM config errors. Subscribing on iOS is harmless and simply never fires.
Syntax
readonly onFcmConfigError: EventEmitter<FcmConfigError>;
The FcmConfigError type is exported for re-use:
import PushEngage, {
type FcmConfigError,
} from '@pushengage/pushengage-react-native';
// FcmConfigError shape:
// {
// code: number;
// message: string;
// }
Usage
import { type EventSubscription } from 'react-native';
const fcmErrorSub = React.useRef<null | EventSubscription>(null);
React.useEffect(() => {
fcmErrorSub.current = PushEngage.onFcmConfigError((error) => {
console.error(`FCM config error ${error.code}: ${error.message}`);
});
return () => {
fcmErrorSub.current?.remove();
fcmErrorSub.current = null;
};
}, []);