civil-and-structural-engineering
Building Multi-platform Notifications with React Native and Onesignal
Table of Contents
Why Multi‑Platform Push Matters for Modern Apps
In today’s fast‑paced mobile ecosystem, users expect to stay informed and engaged regardless of which device they carry. A well‑timed notification can re‑engage a dormant user, drive conversions, or deliver critical updates. Building a notification system that works reliably across iOS, Android, and even the web is no longer a nice‑to‑have — it’s a competitive necessity.
React Native, the cross‑platform framework originally built by Facebook, allows teams to ship native mobile apps using JavaScript and React. Combined with a robust push service like OneSignal, developers can target every major platform from a single codebase. This guide walks through the full integration, from setup to best practices, so you can deliver consistent, high‑quality notifications with minimal overhead.
React Native: The Foundation for Cross‑Platform Development
React Native enables you to write mobile UIs that compile to truly native components on both iOS and Android. Unlike hybrid solutions that rely on WebViews, React Native renders platform‑specific views (like UIView on iOS and View on Android), giving your app the look, feel, and performance users expect. The framework’s “learn once, write anywhere” philosophy has made it a top choice for companies large and small — from Instagram to Shopify to UberEats.
Why React Native for Notifications?
Push notifications in React Native behave exactly like native notifications because the underlying SDKs (APNs for iOS, FCM for Android) are invoked through the platform bridge. This means you get first‑class support for features like:
- Rich media attachments (images, videos, audio)
- Interactive notification buttons
- Notification grouping and summary (Android 7+ / iOS 12+)
- Badge counts and sounds
All of these work out of the box once a proper push service is wired in.
OneSignal: A Unified Push Service
OneSignal is one of the most widely adopted push notification platforms, serving over 1.5 billion devices monthly. It abstracts away the complexity of dealing with Apple Push Notification Service (APNs) and Firebase Cloud Messaging (FCM) directly. Instead, you register once and OneSignal handles delivery, retries, and platform‑specific formatting.
Key Capabilities of OneSignal
- Multi‑platform delivery: Send to iOS, Android, Huawei, Fire OS, and web (Chrome, Safari, Edge, Firefox) from a single API call.
- Segmentation: Target users by device, language, tags, location, or custom properties.
- A/B testing: Test message copy, timing, and media across audience segments.
- Analytics & attribution: Track open rates, click‑through rates, and convert app events.
- Automation: Trigger notifications based on in‑app behavior or external webhooks.
OneSignal also provides a generous free tier, making it accessible to indie developers and startups alike.
Step‑by‑Step Integration: React Native + OneSignal
Below we walk through a complete integration. The steps assume you already have a React Native project (CLI or Expo bare workflow). If you’re using Expo managed workflow, you’ll need to eject or use a custom dev client because OneSignal requires native modules.
1. Create a OneSignal Account and Get Your App ID
Head to OneSignal Dashboard, sign up, and create a new app. Choose “iOS / Android / Other Platforms.” After creation, you’ll find your App ID (a UUID) on the Settings page — copy it. You’ll also need to upload your APNs auth key (or p12 certificate) for iOS and your Firebase server key for Android. OneSignal’s setup wizard will guide you.
2. Install the React Native SDK
In your project root, run:
npm install react-native-onesignal
or if you use Yarn:
yarn add react-native-onesignal
For React Native 0.60+ with autolinking, that’s all. For older versions, you may need to run react-native link react-native-onesignal.
3. Configure Native Endpoints
On iOS, open ios/YourApp/AppDelegate.m and add the OneSignal import and initialization. Your final didFinishLaunchingWithOptions should look something like:
#import <React/RCTBridge.h>
#import <React/RCTRootView.h>
#import <OneSignal/OneSignal.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ... existing bridge setup ...
[OneSignal setAppId:@"YOUR-ONESIGNAL-APP-ID"];
// Optionally set launch options
[OneSignal initWithLaunchOptions:launchOptions];
return YES;
}
On Android, you’ll need to update android/app/src/main/java/.../MainApplication.java to add the OneSignal init:
import com.onesignal.OneSignal;
public class MainApplication extends Application implements ReactApplication {
@Override
public void onCreate() {
super.onCreate();
// ... other init code ...
OneSignal.setAppId("YOUR-ONESIGNAL-APP-ID");
}
}
Don’t forget to add the necessary permissions in AndroidManifest.xml — the SDK usually handles them, but double‑check for devices that require manual opt‑in.
4. Initialize OneSignal in Your JavaScript Entry Point
In your App.js (or index.js), import and set the App ID:
import OneSignal from 'react-native-onesignal';
OneSignal.setAppId('YOUR-ONESIGNAL-APP-ID');
That’s the bare minimum. To listen for notification events, add handlers:
OneSignal.setNotificationWillShowInForegroundHandler(
(notificationReceivedEvent) => {
console.log('Notification received in foreground:', notificationReceivedEvent);
// Complete with notification to display or null to suppress
notificationReceivedEvent.complete(notificationReceivedEvent.notification);
}
);
OneSignal.setNotificationOpenedHandler((notificationOpenedEvent) => {
console.log('Notification opened:', notificationOpenedEvent);
// Navigate user to a specific screen based on data
});
OneSignal will automatically request permission on iOS (where required) and prompt for notification opt‑in on both platforms if needed.
Sending Notifications Across Platforms
Once integrated, you can send notifications in two primary ways:
Via the OneSignal Dashboard
Navigate to Messages → New Push → Push Notification. Enter your title and message. OneSignal previews how it will look on each platform. You can add images, action buttons, and a custom URL. Choose your audience (segments, specific players, or tags) and schedule delivery. OneSignal handles the rest.
Via the REST API (Programmatic)
For automated or server‑side sending, use the OneSignal REST API. Make a POST request to https://onesignal.com/api/v1/notifications with your App ID as a header (Authorization: Basic YOUR_REST_API_KEY). Example JSON payload using fetch in Node.js:
{
"app_id": "YOUR-ONESIGNAL-APP-ID",
"included_segments": ["Active Users"],
"headings": {"en": "New Content Available"},
"contents": {"en": "Tap to explore today’s trending articles."},
"big_picture": "https://example.com/banner.jpg", // Android rich media
"ios_attachments": {"id1": "https://example.com/banner.jpg"}, // iOS rich media
"data": {"screen": "articles"}
}
OneSignal automatically maps the appropriate fields for each platform. You can also target specific player IDs, external user IDs, or email addresses.
Best Practices for Multi‑Platform Notifications
Good notifications are a blend of timing, personalization, and respect for the user’s attention. Below are actionable recommendations.
Personalize Based on Behavior
Use OneSignal tags to store user preferences (e.g., favorite category, last activity date). Send different messages to users who haven’t opened the app in a week vs. daily users. Reference user‑specific data in the message — for example, “Your order #123 has shipped!” instead of a generic “Order update.”
Keep Messages Concise
iOS notifications are limited to roughly 178 characters for the body (longer in iOS 15+ with expanded preview), and Android can handle more but users skim. Lead with the most important information: who, what, and where (action). Avoid jargon.
Respect Platform Conventions
Deep linking works differently across platforms. On iOS, using Universal Links; on Android, use App Links or custom schemes. Make sure the data payload in your notification maps to a route your app can parse. Test on a real device — simulator notifications are unreliable for certain features (e.g., notification grouping).
Test, Test, Test
Use OneSignal’s “Send Test Push” feature to send to a specific device. Verify that:
- Notifications appear on lock screen and notification center
- Rich media (images) render correctly
- Action buttons work and trigger the right handler
- Tapping a notification navigates to the correct screen
- Foreground notifications show a banner (or custom UI) as expected
Manage Opt‑Ins Gracefully
On iOS, the system prompt appears automatically; on Android, you may need to prompt earlier. Provide a clear explanation of what the user will receive (e.g., “We’ll notify you when new episodes drop. No spam.”). If a user declines, don’t ask repeatedly — offer an in‑app settings toggle instead.
Advanced Considerations
Handling Notification Permission States
OneSignal exposes the current permission status. In React Native, you can check and react:
import OneSignal from 'react-native-onesignal';
const deviceState = await OneSignal.getDeviceState();
console.log('Permission:', deviceState.notificationPermissionStatus);
// 0 = NotDetermined, 1 = Authorized, 2 = Denied
Use this to conditionally show a permission‑requesting button or a fallback UI.
Using External User IDs for Cross‑Platform User Identity
If your app has its own authentication system, call OneSignal.setExternalUserId(userId) after login. Then you can target this user across multiple devices (e.g., iPad, Android phone, web) via a single ID. OneSignal will also merge sessions and attributes automatically.
Unsubscribing Users
Respect opt‑outs. When a user disables notifications in system settings, OneSignal automatically marks that device as unsubscribed. You can also programmatically unsubscribe via OneSignal.disablePush(true). This ensures you don’t waste sends or annoy users.
Common Pitfalls and How to Avoid Them
- Missing native initialization: Many issues stem from forgetting to call
setAppIdin native code (iOS/Android). Double‑check that the method runs before any notification events. - Bad APNs/FCM credentials: OneSignal will show “Deliveries” as zero if certificates or server keys are invalid. Regenerate them in the developer consoles and re‑upload in OneSignal Settings.
- Silent notifications not handled: If you send a content‑available (silent) push, ensure your app registers a background handler. OneSignal provides
setNotificationWillShowInForegroundHandleronly for visible foreground notifications; for background silent pushes you need a separate push service extension on iOS or a Firebase messaging service on Android. - Test on production builds: In Debug mode, iOS simulators cannot receive push notifications (APNs is not available). Use a physical device or a real device cloud service.
Conclusion
Building a multi‑platform notification system no longer requires maintaining separate push implementations for iOS, Android, and the web. React Native gives you a shared codebase for mobile UIs, and OneSignal provides a battle‑tested layer for reliable, feature‑rich push delivery. By following the integration steps above and applying the best practices outlined, you can deliver engaging, timely notifications that users appreciate — without adding weeks of extra development effort.
For further reading, explore the official OneSignal Documentation and the React Native Push Notifications Guide. Start small, test thoroughly, and iterate based on your audience’s behavior.