{"id":15205,"library":"react-onesignal","title":"React OneSignal Integration","description":"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.","status":"active","version":"3.5.1","language":"javascript","source_language":"en","source_url":"https://github.com/OneSignal/react-onesignal","tags":["javascript","onesignal","push","notification","push notification","react","typescript"],"install":[{"cmd":"npm install react-onesignal","lang":"bash","label":"npm"},{"cmd":"yarn add react-onesignal","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-onesignal","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses ES Module syntax. While CommonJS is supported since v3.3.0, ESM is the recommended pattern for modern React applications. OneSignal is a default export.","wrong":"const OneSignal = require('react-onesignal');","symbol":"OneSignal","correct":"import OneSignal from 'react-onesignal';"},{"note":"This is a TypeScript type interface, requiring a type-only import for correct static analysis and to avoid bundling issues.","wrong":"import { IDisplayableOSNotification } from 'react-onesignal';","symbol":"IDisplayableOSNotification","correct":"import type { IDisplayableOSNotification } from 'react-onesignal';"},{"note":"Slidedown is a property of the initialized OneSignal object, not a separate named export. Access it after OneSignal has been successfully initialized.","wrong":"import { Slidedown } from 'react-onesignal';","symbol":"Slidedown","correct":"await OneSignal.init({ appId: 'YOUR_APP_ID' });\nOneSignal.Slidedown.promptPush();"}],"quickstart":{"code":"import React, { useState, useEffect } from 'react';\nimport OneSignal from 'react-onesignal';\n\nfunction PushNotificationHandler() {\n  const [initialized, setInitialized] = useState(false);\n\n  useEffect(() => {\n    const initializeOneSignal = async () => {\n      try {\n        await OneSignal.init({\n          appId: process.env.ONE_SIGNAL_APP_ID ?? 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',\n          safari_web_id: process.env.ONE_SIGNAL_SAFARI_WEB_ID ?? '',\n          notifyButton: {\n            enable: true,\n          },\n          allowLocalhostAsSecureOrigin: true,\n        });\n        setInitialized(true);\n        console.log('OneSignal initialized successfully');\n        \n        // You can prompt for push notifications here after initialization\n        // OneSignal.Slidedown.promptPush();\n\n      } catch (error) {\n        console.error('Failed to initialize OneSignal:', error);\n      }\n    };\n\n    if (!initialized) {\n      initializeOneSignal();\n    }\n  }, [initialized]);\n\n  if (!initialized) {\n    return <div>Loading push notifications...</div>;\n  }\n\n  return (\n    <div>\n      <h1>Push Notifications Ready</h1>\n      <p>OneSignal SDK is initialized and ready to use.</p>\n      <button onClick={() => OneSignal.Slidedown.promptPush()}>Show Push Prompt</button>\n    </div>\n  );\n}\n\nexport default PushNotificationHandler;","lang":"typescript","description":"This example demonstrates how to initialize OneSignal using the `init` function within a React component's `useEffect` hook, ensuring it's called only once. It shows how to await the initialization promise and conditionally render content based on the SDK's readiness."},"warnings":[{"fix":"Refer to the 'MigrationGuide.md' file in the package's GitHub repository or documentation to adapt your code to the v3 API changes.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always use `await OneSignal.init(...)` in an `async` context or `OneSignal.init(...).then(() => { ... })` to ensure the SDK is fully loaded and ready before subsequent calls.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Understand that the package provides an API wrapper, not React components. Integrate it by calling its `init` method and then using the exposed OneSignal SDK methods.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Ensure that the service worker paths specified in the `init` options correctly point to the OneSignal service worker files within your deployed application. Verify these paths against your OneSignal setup and deployment structure.","message":"Incorrect configuration of `path`, `serviceWorkerPath`, or `serviceWorkerUpdaterPath` options during `init` can lead to service worker registration failures, preventing push notifications from working correctly.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"When using notification event listeners and `event.preventDefault()`, ensure you understand the lifecycle. If the notification should eventually be shown, explicitly call `notification.display()` at the appropriate time.","message":"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.","severity":"gotcha","affected_versions":">=3.5.1"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `import OneSignal from 'react-onesignal';` is at the top of your file, or use `const OneSignal = require('react-onesignal');` for CJS.","cause":"Attempting to use `OneSignal` without importing it, or in a CommonJS environment without correctly requiring it after v3.3.0.","error":"ReferenceError: OneSignal is not defined"},{"fix":"Always `await OneSignal.init(...)` or chain `.then()` to the `init` call before attempting to interact with other OneSignal SDK functionalities.","cause":"Calling OneSignal methods (e.g., `Slidedown.promptPush()`) before the `OneSignal.init()` promise has resolved.","error":"TypeError: Cannot read properties of undefined (reading 'promptPush')"},{"fix":"Verify 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.","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.","error":"OneSignal SDK is not initialized."},{"fix":"Double-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.","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.","error":"Failed to register service worker"}],"ecosystem":"npm"}