React OneSignal Integration
react-onesignal is a JavaScript/TypeScript module designed to streamline the integration of OneSignal's push notification, web push, and in-app messaging services into web applications. Currently at version 3.5.1, the library receives frequent patch and minor updates, indicating active development. While its name suggests a React-specific use, the library's documentation explicitly states it can be used in virtually any JavaScript front-end codebase. It acts as a wrapper around the OneSignal Web SDK, abstracting the direct script loading and providing a convenient, promise-based `init` method to configure the SDK. Key differentiators include its React-friendly API, managed script loading (with an option to override the script source), and strong TypeScript support, simplifying the development experience for push notification capabilities.
Common errors
-
ReferenceError: OneSignal is not defined
cause Attempting to use `OneSignal` without importing it, or in a CommonJS environment without correctly requiring it after v3.3.0.fixEnsure `import OneSignal from 'react-onesignal';` is at the top of your file, or use `const OneSignal = require('react-onesignal');` for CJS. -
TypeError: Cannot read properties of undefined (reading 'promptPush')
cause Calling OneSignal methods (e.g., `Slidedown.promptPush()`) before the `OneSignal.init()` promise has resolved.fixAlways `await OneSignal.init(...)` or chain `.then()` to the `init` call before attempting to interact with other OneSignal SDK functionalities. -
OneSignal SDK is not initialized.
cause This error occurs internally within the OneSignal SDK if you try to use its methods (e.g., `setExternalUserId`, `sendTag`) when `OneSignal.init()` has not been successfully called or completed.fixVerify that `OneSignal.init()` is called exactly once and its promise resolves successfully before any other OneSignal API calls. Check for any errors during the `init` process. -
Failed to register service worker
cause The OneSignal service worker file is not found at the specified `path`, `serviceWorkerPath`, or `serviceWorkerUpdaterPath` during initialization, or there are network/CORS issues preventing its loading.fixDouble-check the paths provided in the `init` options match the location of your OneSignal service worker files. Ensure these files are correctly deployed and accessible from your domain. Use browser developer tools to inspect service worker registration errors.
Warnings
- breaking Version 3.0 introduced significant breaking changes. Existing implementations using v2.x or older will require updates. Consult the official 'Migration Guide' for detailed instructions.
- gotcha The `OneSignal.init()` function returns a Promise. It is crucial to await this promise or use its `.then()` method before attempting to call any other OneSignal SDK methods, otherwise, they might not be available or fully configured.
- gotcha While the package is named `react-onesignal`, it's explicitly stated to be usable in 'practically any JS front-end codebase'. Developers should be aware it's a wrapper for the OneSignal Web SDK and not a React-specific UI component library.
- gotcha Incorrect configuration of `path`, `serviceWorkerPath`, or `serviceWorkerUpdaterPath` options during `init` can lead to service worker registration failures, preventing push notifications from working correctly.
- gotcha The `IDisplayableOSNotification` interface and its `display()` method (added in v3.5.1) are for advanced notification handling. Misusing `preventDefault()` without subsequently calling `display()` (if intended) can result in notifications not being shown to the user.
Install
-
npm install react-onesignal -
yarn add react-onesignal -
pnpm add react-onesignal
Imports
- OneSignal
const OneSignal = require('react-onesignal');import OneSignal from 'react-onesignal';
- IDisplayableOSNotification
import { IDisplayableOSNotification } from 'react-onesignal';import type { IDisplayableOSNotification } from 'react-onesignal'; - Slidedown
import { Slidedown } from 'react-onesignal';await OneSignal.init({ appId: 'YOUR_APP_ID' }); OneSignal.Slidedown.promptPush();
Quickstart
import React, { useState, useEffect } from 'react';
import OneSignal from 'react-onesignal';
function PushNotificationHandler() {
const [initialized, setInitialized] = useState(false);
useEffect(() => {
const initializeOneSignal = async () => {
try {
await OneSignal.init({
appId: process.env.ONE_SIGNAL_APP_ID ?? 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
safari_web_id: process.env.ONE_SIGNAL_SAFARI_WEB_ID ?? '',
notifyButton: {
enable: true,
},
allowLocalhostAsSecureOrigin: true,
});
setInitialized(true);
console.log('OneSignal initialized successfully');
// You can prompt for push notifications here after initialization
// OneSignal.Slidedown.promptPush();
} catch (error) {
console.error('Failed to initialize OneSignal:', error);
}
};
if (!initialized) {
initializeOneSignal();
}
}, [initialized]);
if (!initialized) {
return <div>Loading push notifications...</div>;
}
return (
<div>
<h1>Push Notifications Ready</h1>
<p>OneSignal SDK is initialized and ready to use.</p>
<button onClick={() => OneSignal.Slidedown.promptPush()}>Show Push Prompt</button>
</div>
);
}
export default PushNotificationHandler;