Skip to main content

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.

npm GitHub release

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.

note

This method must be called before using any other SDK features. It associates all subsequent operations with your specific PushEngage application.

Syntax

TypeScript
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

TypeScript
PushEngage.setAppId('YOUR_APP_PUSH_ID');
Best Practices
  • 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.

Call before setAppId

setEnvironment must be invoked before setAppId. Switching the environment after initialization is unsupported and may leave the subscriber registered against the previous environment.

Syntax

TypeScript
setEnvironment: (environment: 'STAGING' | 'PRODUCTION') => void

The Environment type is also exported for re-use:

TypeScript
import PushEngage, {
type Environment,
} from '@pushengage/pushengage-react-native';

const env: Environment = 'PRODUCTION';

Parameters

environment: 'STAGING' or 'PRODUCTION'.

Usage

TypeScript
PushEngage.setEnvironment('PRODUCTION');
PushEngage.setAppId('YOUR_APP_PUSH_ID');

enableLogging

Enable or disable logging for the PushEngage SDK.

Syntax

TypeScript
enableLogging: (shouldEnable: boolean) => void

Parameters

shouldEnable: Boolean indicating whether logging should be enabled (true) or disabled (false).

Usage

TypeScript
// 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

TypeScript
requestNotificationPermission: () => Promise<boolean>;

Returns

Promise resolving to:

true: Permission granted

false: Permission denied/rejected

Usage

TypeScript
const isGranted: boolean = await PushEngage.requestNotificationPermission();

Common Use Cases

  1. First time app-launch
TypeScript
// In your onboarding flow
async function onboardingComplete() {
const hasPermission = await PushEngage.requestNotificationPermission();
if (hasPermission) {
// Add your code implementation here
}
}
  1. Feature-specific permission
TypeScript
// When enabling a feature that needs notifications
async function enableDeliveryUpdates() {
const hasPermission = await PushEngage.requestNotificationPermission();
if (hasPermission) {
// Add your code implementation here
}
}
Best Practices
  • 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

TypeScript
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

TypeScript
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

TypeScript
subscribe: () => Promise<void>;

Returns

Promise that resolves when subscribe operation completes successfully, or throws an error if the operation fails.

Usage

TypeScript
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

TypeScript
unsubscribe: () => Promise<void>;

Returns

Promise that resolves when unsubscribe operation completes successfully, or throws an error if the operation fails.

Usage

TypeScript
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

TypeScript
getSubscriptionStatus: () => Promise<boolean>;

Returns

Promise resolving to:

  • true: User is subscribed to push notifications
  • false: User is not subscribed (unsubscribed or never subscribed)

Usage

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
getSubscriberId: () => Promise<string | null>;

Returns

Promise resolving to:

  • string: The subscriber ID if the user is subscribed
  • null: If the user is not subscribed

Usage

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
identify: (fields: IdentifyFields) => Promise<void>;

The IdentifyFields type is exported for re-use:

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

KeyTypeDescription
first_namestring | number | booleanSubscriber's first name
last_namestring | number | booleanSubscriber's last name
emailstring | number | booleanEmail address
phonestring | number | booleanPhone number
genderstring | number | booleanGender
dobstring | number | booleanDate of birth
languagestring | number | booleanLocale/language code
profile_idstring | number | booleanYour own user ID; numeric values are auto-coerced to string
countrystring | number | booleanCountry
citystring | number | booleanCity
statestring | number | booleanState / region
zipstring | number | booleanPostal code

Usage

TypeScript
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

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

Validation

The wrapper rejects with a TypeError at the JS boundary when fieldNames is an array containing a non-string element.

Usage

TypeScript
// 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

TypeScript
trackEvent: (event: TrackEventPayload) => Promise<void>;

The TrackEventPayload type is exported for re-use:

TypeScript
import PushEngage, {
type TrackEventPayload,
} from '@pushengage/pushengage-react-native';

Parameters

event: A TrackEventPayload object describing the event.

FieldTypeRequiredDescription
eventNamestringYesName of the event (e.g., "MySite.AddToCart").
dataobjectNoCustom key-value data. Values must be string, number, or boolean.
profileIdstringNoProfile ID of the subscriber.
providerstringNoProvider name. Defaults to "PushEngage".
eventTypestringNoEvent type. Defaults to "PushEngage.CustomEvent".

Usage

TypeScript
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

TypeScript
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 details
  • null: If no details are available (the promise rejects if the lookup fails)

Usage

TypeScript
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

FieldTypeDescription
citystringSubscriber's city
statestringSubscriber's state or region
countrystringSubscriber's country
devicestringDevice name
device_typestringDevice type (e.g., mobile, tablet)
user_agentstringApp user agent string
hoststringHost identifier
timezonestringSubscriber's timezone
has_unsubscribedbooleanWhether the subscriber has unsubscribed
ts_createdstringISO 8601 timestamp of subscription creation
segmentsarraySegment 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.

  1. Log in to your PushEngage Dashboard.
  2. Navigate to the Audience section.
  3. Select Segments and click Create a New Segment.
  4. Define the segment name and criteria and save it.

addSegment

This method enables you to add the current subscriber to segments.

Syntax

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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

TypeScript
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
TypeScript
await PushEngage.automatedNotification(true);
Disable Automated Notifications
TypeScript
await PushEngage.automatedNotification(false);

For a reusable pattern:

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

  1. Log in to your PushEngage Dashboard.
  2. Navigate to the Campaign section.
  3. Select Triggered Campaigns and click Create New Triggered Campaign.
  4. Select from either of the following options:
    • Custom Trigger Campaign
    • Browse Abandonment
    • Cart Abandonment
  5. Define the trigger conditions and customize the notification content.

Syntax

TypeScript
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

TypeScript
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);
}
}
note

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.

  1. Log in to your PushEngage Dashboard.
  2. Navigate to the Campaign section.
  3. Select Triggered Campaigns and click Create New Triggered Campaign.
  4. Select from either of the following options:
    • Price Drop
    • Back in Stock Alert
  5. Define the trigger conditions and customize the notification content.

Syntax

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

  1. Log in to your PushEngage Dashboard.
  2. Navigate to the Analytics section.
  3. Select Goal Tracking and tick Enable Goal Tracking.

Syntax

TypeScript
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

TypeScript
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);
}
}
note

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

TypeScript
readonly onValueChanged: EventEmitter<{
deepLink: string;
data: { [key: string]: string };
}>

Returns

TypeScript
type DeepLinkData = {
deepLink: string; // The deep link URL/string
data: Record<string, string>; // Additional data payload
};

Usage

TypeScript
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.
Best Practices
  • 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).

iOS only

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

TypeScript
getInitialNotification: () => Promise<InitialNotification | null>;

The InitialNotification type is exported for re-use:

TypeScript
import PushEngage, {
type InitialNotification,
} from '@pushengage/pushengage-react-native';

Returns

Promise resolving to:

  • InitialNotification object — 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

TypeScript
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

TypeScript
getSdkVersion: () => string;

Returns

A String representing the current version of the PushEngage React Native SDK.

Usage

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

Android only

Only Android applies the resource name to outgoing notifications. On iOS the call is a no-op — the promise resolves with no value.

Syntax

TypeScript
setSmallIconResource: (resourceName: string) => Promise<void>;

Parameters

resourceName: A string representing the resource name of the small icon.

Usage

TypeScript
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);
}
}
}
note

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.setBadgeCount on iOS 16+, with applicationIconBadgeNumber fallback 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 0 additionally clears all active notifications (via NotificationManagerCompat.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

TypeScript
setBadgeCount: (count: number) => void;

Parameters

count: The badge count. Pass 0 to clear the badge.

Usage

TypeScript
// 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

TypeScript
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

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

CodeMeaning
5001FCM_SENDER_ID_MISMATCHgoogle-services.json sender ID does not match the dashboard.
5002FCM_PROJECT_ID_MISMATCHgoogle-services.json project ID does not match the service-account JSON.
5003FCM_LOCAL_CONFIG_INVALID — Firebase Installations rejected google-services.json as invalid for the app.
5004FCM_CONFIG_BOTH_MISMATCH — both sender ID and project ID differ from the dashboard configuration.
iOS no-op

The native iOS bridge does not emit FCM config errors. Subscribing on iOS is harmless and simply never fires.

Syntax

TypeScript
readonly onFcmConfigError: EventEmitter<FcmConfigError>;

The FcmConfigError type is exported for re-use:

TypeScript
import PushEngage, {
type FcmConfigError,
} from '@pushengage/pushengage-react-native';

// FcmConfigError shape:
// {
// code: number;
// message: string;
// }

Usage

TypeScript
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;
};
}, []);