Push notifications have become essential for mobile app engagement, enabling developers to re-engage users with timely, relevant messages. React Native developers can implement push notifications efficiently using OneSignal, a powerful cross-platform notification service that supports iOS, Android, and web platforms from a single codebase. This guide walks through the complete implementation process, from initial setup to production-ready configuration.
Why Use OneSignal for React Native Push Notifications
OneSignal has established itself as a leading push notification provider for mobile and web applications, offering a comprehensive platform that simplifies the complexity of cross-platform notification delivery. For React Native developers, OneSignal provides significant advantages that make it an attractive choice for projects of any scale.
The platform handles the underlying infrastructure required for push notifications, including Apple Push Notification service (APNs) for iOS and Firebase Cloud Messaging (FCM) for Android, eliminating the need for developers to manage separate notification services for each platform. This abstraction allows teams to focus on building notification features rather than managing platform-specific delivery systems. The SDK offers a unified API that abstracts platform differences, meaning developers write notification logic once and deploy across iOS and Android without platform-specific code modifications.
OneSignal's free tier includes unlimited push notifications with a generous monthly limit, making it accessible for startups and enterprise applications alike. The platform supports advanced features including rich media notifications, localization, user segmentation, A/B testing, and detailed analytics dashboards that provide insights into notification performance and user engagement metrics. This comprehensive approach to mobile communication aligns well with our mobile application development services, where push notification integration is a key feature for customer engagement.
Why React Native developers choose OneSignal for push notifications
Unified Cross-Platform API
Write notification logic once and deploy across iOS and Android without platform-specific code modifications, significantly reducing development time and maintenance overhead.
Advanced Segmentation
Target specific user groups based on behavior, location, device type, or custom tags to ensure notifications remain relevant to each recipient.
Rich Analytics Dashboard
Access detailed insights into notification delivery rates, open rates, and user interactions for data-driven optimization of notification strategies.
Multi-Channel Support
Support push notifications, in-app messaging, email, and SMS from a single platform as your communication needs expand.
Prerequisites and Project Setup
Before implementing OneSignal push notifications in a React Native project, several prerequisites must be satisfied to ensure a smooth integration process. Understanding these requirements upfront prevents common configuration issues that can delay implementation.
Required Development Environment
React Native 0.71 or newer is recommended for OneSignal integration, as the SDK has been optimized for modern React Native architecture patterns. Projects using older React Native versions may encounter compatibility issues and should consider upgrading before implementing push notifications. The SDK supports both the new architecture (TurboModules) and legacy architecture, ensuring compatibility across different project configurations.
iOS Requirements:
- Xcode 14 or newer
- Valid Apple Developer account with push notification capabilities
- CocoaPods 1.16.2 or newer
- Physical iOS device for testing (simulator does not support push notifications)
Android Requirements:
- Android Studio with latest SDK tools
- Android device or emulator running Android 7.0 (API level 24) or higher
- Google Play Services installed on emulator
OneSignal Account and App Configuration
A OneSignal account is required to access the dashboard and obtain necessary credentials. The free account provides access to all core features needed for standard push notification implementation, including unlimited notifications up to 30,000 per month. Creating an app entry in the OneSignal dashboard generates an App ID that identifies the application within the OneSignal platform.
Within the OneSignal dashboard, platform credentials must be configured for each target platform. For Android, a Firebase Cloud Messaging server key and sender ID are required, which can be obtained from the Firebase Console by creating or selecting an existing Firebase project. For iOS, either an Apple Push Notification Authentication Key (recommended) or p12 certificates can be used to authenticate with APNs. These credentials are entered in the OneSignal dashboard under the app's settings, enabling the platform to deliver notifications to each respective device ecosystem. Proper configuration is essential for reliable notification delivery across both platforms.
Installing the OneSignal React Native SDK
The OneSignal React Native SDK provides a native module interface for React Native applications, handling the complexity of device token registration, notification handling, and platform-specific communication. Installing the SDK follows standard React Native package management procedures, with platform-specific post-installation steps for iOS.
Package Installation
npm install react-native-onesignal
# or
yarn add react-native-onesignal
The SDK is distributed as an npm package and can be installed using either npm or yarn, depending on the project's package manager preference. For projects using React Native versions prior to 0.60, manual linking may be required, though modern React Native versions handle linking automatically through the community's autolinking system.
iOS Post-Installation Configuration
After installing the npm package, iOS projects require additional configuration to properly integrate the OneSignal SDK. Running pod install within the iOS directory installs the native SDK dependencies managed through CocoaPods. This step is essential and cannot be skipped, as the OneSignal SDK relies on native components that must be compiled into the iOS application.
cd ios && pod install && cd ..
The iOS project must also be configured to include the OneSignal SDK in the Podfile, though the pod install command typically handles this automatically. For projects with custom Podfile configurations, ensuring the OneSignal pod is properly specified prevents build errors during the compilation phase.
Android Configuration
Android projects typically require minimal post-installation configuration for OneSignal integration. The SDK uses AndroidX libraries, so projects must ensure AndroidX compatibility is enabled in the android/gradle.properties file. Modern React Native projects generated with version 0.60 or newer have AndroidX enabled by default.
The android/build.gradle file should include the OneSignal maven repository in the allprojects section, ensuring the SDK artifacts can be downloaded during the build process. Projects using React Native 0.73 or newer with the New Architecture enabled should verify that the SDK's native modules are properly configured, though OneSignal provides compatibility support for both legacy and new architecture implementations.
Platform-Specific Configuration
Proper platform configuration is critical for push notification functionality, as each mobile platform requires specific credentials and permission configurations that differ significantly between iOS and Android. Understanding these requirements ensures notifications can be delivered reliably to devices on both platforms.
Android FCM Configuration
Android push notifications route through Firebase Cloud Messaging, requiring a Firebase project configured with FCM capabilities. Creating a Firebase project through the Firebase Console generates a google-services.json file that must be added to the Android project directory. This file contains the API keys and configuration data that enable OneSignal to communicate with FCM on behalf of the application.
Required setup steps:
- Create Firebase project in Firebase Console
- Add Android app with your package name
- Download google-services.json to android/app/
- Add google-services plugin to build.gradle files
- Enter FCM credentials in OneSignal dashboard
The google-services.json file is placed in the android/app/ directory of the React Native project, and the Android application build configuration must reference this file through the gradle plugin. The project's android/build.gradle and android/app/build.gradle files should include the google-services plugin configuration, enabling the build system to incorporate the Firebase credentials into the compiled application.
iOS APNs Configuration
Apple Push Notification service configuration requires credentials from the Apple Developer portal, where push notification capabilities must be explicitly enabled for the application's App ID. Creating an Auth Key in the Apple Developer portal provides the recommended authentication method, as p8 tokens do not expire and can be used across multiple applications without renewal.
Required setup steps:
- Enable Push Notifications capability in Apple Developer portal
- Create Auth Key (.p8) for APNs authentication
- Configure credentials in OneSignal dashboard
- Verify Background Modes includes Remote Notifications in Xcode
The Auth Key file (.p8) and key ID, along with the Team ID and bundle identifier, are configured in the OneSignal dashboard for the iOS platform. OneSignal uses these credentials to authenticate with Apple's servers when delivering notifications to iOS devices. Xcode project configuration ensures the application requests and receives push notification permissions from users.
Initializing OneSignal in the Application
With the SDK installed and platform credentials configured, the application code must initialize OneSignal to begin receiving device tokens and handling notifications. Initialization establishes the connection between the React Native application and OneSignal's servers, enabling push notification functionality.
SDK Initialization
import OneSignal from 'react-native-onesignal';
// Initialize OneSignal
OneSignal.initialize('YOUR_ONESIGNAL_APP_ID');
// Configure notification behavior
OneSignal.Notifications.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
console.log('Notification received in foreground:', notificationReceivedEvent);
});
OneSignal.Notifications.setNotificationOpenedHandler(notification => {
console.log('Notification opened:', notification);
});
The OneSignal SDK is initialized during application startup, typically within the root component's useEffect hook or in a dedicated notification service file that initializes before the application renders. The initialization call requires the OneSignal App ID obtained from the dashboard and configures notification behavior preferences.
Requesting User Permission
iOS requires explicit user permission before push notifications can be delivered to the device. The permission request should be triggered by a user action, such as tapping a "Enable Notifications" button, rather than automatically on application launch. This approach aligns with Apple's guidelines and provides better user experience by setting context before requesting consent.
import OneSignal from 'react-native-onesignal';
async function requestNotificationPermission() {
const permission = await OneSignal.Notifications.requestPermission(true);
console.log('Notification permission granted:', permission);
}
Android Note: Applications targeting API level 33 (Android 13) or higher must declare the POST_NOTIFICATIONS permission in AndroidManifest.xml and request this permission at runtime. Android applications targeting older versions receive permissions automatically upon installation, though users can disable notifications through system settings at any time. Our mobile development team follows these best practices to ensure optimal user permission rates for production applications.
Creating and Sending Notifications
Once the SDK is initialized and permissions are granted, the application can receive push notifications sent through the OneSignal dashboard or API. Notifications are typically created in the OneSignal dashboard for manual sending or through the REST API for automated notification delivery triggered by application events.
Dashboard Notification Creation
The OneSignal dashboard provides a visual interface for creating and targeting notifications without writing code. Users can compose notification content, select targeting options such as segments or filters, schedule delivery timing, and review delivery statistics after sending. This approach suits marketing notifications, announcements, and other manually-created messages.
The dashboard supports rich notification content including images, buttons, and big picture notifications that display expanded content on supported devices. Notification templates can be saved for recurring notification types, enabling consistent branding and reducing the time required to create similar notifications multiple times.
API-Based Notification Delivery
For automated notification delivery triggered by application events, the OneSignal REST API enables programmatic notification creation from backend servers. A typical implementation sends notifications when significant events occur, such as new messages, order updates, or time-sensitive alerts.
// Example: Sending notification via OneSignal API (server-side)
async function sendPushNotification(userId, title, message) {
const response = await fetch('https://onesignal.com/api/v1/notifications', {
method: 'POST',
headers: {
'Authorization': `Basic ${process.env.ONESIGNAL_REST_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
app_id: process.env.ONESIGNAL_APP_ID,
include_player_ids: [userId],
headings: { en: title },
contents: { en: message },
}),
});
return response.json();
}
The API requires the REST API key available from the OneSignal dashboard and accepts various targeting parameters including specific device tokens, segment filters, or user tags. This programmatic approach integrates seamlessly with backend systems built using our API development services, enabling automated notification workflows triggered by business logic.
Handling Notification Events
React Native applications must handle notification events across different application states, including when the application is in the foreground, background, or completely closed. The OneSignal SDK provides event handlers for each scenario, enabling applications to respond appropriately to notification interactions.
Foreground Notification Handling
When the application is active and visible on screen, notifications trigger the foreground handler rather than displaying in the system notification tray. Applications typically display custom in-app notifications or update UI state based on the notification content.
OneSignal.Notifications.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
// Prevent default notification display
notificationReceivedEvent.preventDefault();
// Get notification data
const notification = notificationReceivedEvent.getNotification();
// Display custom in-app notification or update state
dispatch(showInAppNotification(notification));
// Complete the handler to indicate processing is done
notificationReceivedEvent.complete(notification);
});
The foreground handler receives a notification event object containing the notification title, body, and any additional data payload. Calling preventDefault() prevents the default system notification from displaying, allowing the application to implement custom notification presentation. Calling complete() indicates the handler has finished processing, which is required for the SDK to function correctly.
Background and Closed State Handling
When the user taps a notification while the application is in the background or closed, the notification opened handler fires with details about the notification and any additional data payload.
OneSignal.Notifications.setNotificationOpenedHandler(notification => {
const { actionId, additionalData } = notification;
// Navigate based on notification data
if (additionalData?.screen === 'messages') {
navigation.navigate('Messages', { conversationId: additionalData.conversationId });
} else if (additionalData?.screen === 'orders') {
navigation.navigate('Orders', { orderId: additionalData.orderId });
}
});
Data Payloads and Custom Actions
{
"app_id": "YOUR_APP_ID",
"include_player_ids": ["DEVICE_TOKEN"],
"headings": { "en": "New Message" },
"contents": { "en": "You have a new message from John" },
"data": {
"screen": "messages",
"conversationId": "conv_12345"
},
"buttons": [
{ "id": "reply", "text": "Reply" },
{ "id": "view", "text": "View" }
]
}
Notification buttons appear as action buttons on the system notification, enabling users to respond or take action directly from the notification shade. Button clicks trigger the notification opened handler with the button ID, allowing the application to handle each action appropriately.
User Identification and Tagging
OneSignal's tagging system enables applications to segment users based on attributes, behavior, or preferences, supporting targeted notification delivery to specific user groups. Tags are key-value pairs associated with user devices and can be set, updated, or removed throughout the application lifecycle.
Setting and Managing Tags
// Set user tags
OneSignal.User.addTags({
user_type: 'premium',
favorite_category: 'sports',
notification_preference: 'daily_digest'
});
// Remove a tag
OneSignal.User.removeTag('old_category');
// Get all tags
const tags = await OneSignal.User.getTags();
Tags can be used for audience segmentation within the OneSignal dashboard, enabling notifications to target users matching specific criteria. For example, users tagged with "favorite_category: sports" could receive notifications about sports-related content, while users tagged with "notification_preference: daily_digest" receive summary notifications rather than immediate alerts.
External User Identification
For applications with existing user accounts, OneSignal's external user ID feature associates OneSignal device records with application user accounts, simplifying notification targeting and enabling cross-device user tracking.
// Associate OneSignal with external user ID
OneSignal.User.addExternalUserId('USER_ID_FROM_YOUR_DATABASE');
// Remove association
OneSignal.User.removeExternalUserId();
Setting an external user ID before sending notifications enables the API to target users by their application user ID rather than device tokens, abstracting device-level details from notification delivery logic. This approach is particularly valuable for applications supporting multiple devices per user account, which is common in apps integrated with our customer engagement platforms.
Best Practices for Production Deployment
Implementing push notifications in production requires attention to reliability, user experience, and performance considerations that may not be apparent during initial development. Following established best practices ensures notifications enhance rather than detract from the user experience.
Permission Request Strategy
Requesting notification permissions at the right moment significantly impacts consent rates and user perception. Best practice indicates requesting permissions after the user has experienced value from the application, such as after completing onboarding, making a purchase, or achieving a milestone. Requesting permissions immediately on first launch often results in lower consent rates as users deny permissions without understanding the value proposition.
Applications should also provide educational UI explaining notification benefits before triggering the system permission dialog. This pre-education sets expectations and increases the likelihood of users granting permissions. For users who deny permissions, providing a path to re-enable notifications through device settings demonstrates respect for user choice while ensuring users know how to opt back in if they change their mind.
Notification Content Guidelines
Effective push notification content balances engagement with respect for user attention. Notifications should provide clear value, use actionable language, and include enough context for users to understand relevance without requiring application opening. Testing different notification variations through OneSignal's A/B testing feature helps identify content that resonates with the user base.
- Provide clear value in each notification
- Use actionable language
- Include enough context for users to understand relevance
- Test different variations through A/B testing
- Monitor and adjust frequency to prevent notification fatigue
Analytics and Optimization
OneSignal's analytics dashboard provides essential metrics for understanding notification performance, including delivery rates, open rates, and conversion metrics when linked to analytics tools. Tracking these metrics over time identifies trends and opportunities for optimization.
Segment performance comparison reveals which user groups respond best to notifications, enabling refinement of targeting strategies. Open rate trends indicate whether notification frequency or content needs adjustment, as declining open rates often signal notification fatigue.
Testing and Troubleshooting
Thorough testing across devices and scenarios ensures reliable push notification functionality before production deployment. Common issues typically relate to permission handling, credential configuration, or event handler registration timing.
Device Testing
Testing push notifications requires physical devices for both iOS and Android, as emulators provide limited or inconsistent notification functionality. Testing should cover notification delivery when the application is in foreground, background, and closed states, verifying that event handlers fire correctly in each scenario.
The OneSignal dashboard provides a notification creation tool specifically for testing, enabling quick notification delivery to specific devices without writing API code. This tool should be used to verify that credentials are correctly configured before testing more complex notification scenarios.
Common Issues and Solutions
| Issue | Solution |
|---|---|
| Notifications not delivering | Verify credential configuration in OneSignal dashboard |
| Foreground handler not firing | Move initialization to application startup |
| Permission denied | Implement re-prompt flow with educational context |
| iOS build errors | Run pod install in iOS directory |
Conclusion
Implementing push notifications with OneSignal in React Native provides a robust, cross-platform solution that handles the complexity of push notification delivery while offering advanced features for targeting, personalization, and analytics. The SDK's unified API enables developers to write platform-agnostic notification code while OneSignal manages the underlying infrastructure for both iOS and Android delivery.
Successful implementation requires attention to permission request timing, platform credential configuration, and event handler architecture. Following the practices outlined in this guide ensures a smooth implementation process and reliable production notification functionality that enhances user engagement without degrading user experience. For organizations seeking to integrate push notifications into their mobile strategy, our web development team can provide comprehensive implementation support.
Frequently Asked Questions
Sources
- OneSignal React Native SDK Setup - Primary reference for SDK installation, configuration, and platform-specific setup
- OneSignal Mobile SDK Setup Overview - Platform credential setup and configuration
- LogRocket OneSignal React Native Tutorial - Practical implementation examples and code walkthroughs
- Courier React Native Push Notifications Guide - Additional context on push notification patterns and best practices