ReactJS & NextJS Setup
Add OneSignal to your ReactJS or NextJS website.
Requirements
- OneSignal Account
- Your OneSignal App ID, available in Settings > Keys & IDs.
If you have not done so already, you may benefit from following our Web Push Quickstart first.
Migration Guide
Version 3.0 was recently released. Read the Migration Guide here if you're coming from a version 2 release of the SDK.
Install
Yarn
yarn add react-onesignal
npm
npm install --save react-onesignal
Setup
1. Add the init code
Initialize OneSignal with your appId
found in Keys & IDs:
"use client";
import { useEffect } from 'react';
import OneSignal from 'react-onesignal';
export default function Page() {
useEffect(() => {
// Ensure this code runs only on the client side
if (typeof window !== 'undefined') {
OneSignal.init({
appId: 'YOUR_APP_ID',
// You can add other initialization options here
notifyButton: {
enable: true,
},
// Uncomment the below line to run on localhost. See: https://documentation.onesignal.com/docs/local-testing
// allowLocalhostAsSecureOrigin: true
});
}
}, []);
return (
<div>
<h1>Hello, world!</h1>
{/* Rest of your page content */}
</div>
);
}
Calling useEffect in development mode may cause the SDK to Initialize Twice
When testing in a development environment, you may find that your OneSignal SDK is initialized twice and therefore produces a console error.
To resolve this, remove the <React.StrictMode> component from your root.
(Strict mode checks are run in development mode only; they do not impact the production build.)
2. Add the service worker
If you haven't done so already, you will need to download the OneSignal Service Worker file to add to your site.
The OneSignalSDKWorker.js
file must be publicly accessible. You can put it in your public
directory, top-level root, or a subdirectory. However, if you are placing the file in a subdirectory and/or have another service worker for your site, then make sure to specify the path. See OneSignal Service Worker for details.
OneSignal API
Typescript
This package includes Typescript support.
interface IOneSignalOneSignal {
Slidedown: IOneSignalSlidedown;
Notifications: IOneSignalNotifications;
Session: IOneSignalSession;
User: IOneSignalUser;
Debug: IOneSignalDebug;
login(externalId: string, jwtToken?: string): Promise<void>;
logout(): Promise<void>;
init(options: IInitObject): Promise<void>;
setConsentGiven(consent: boolean): Promise<void>;
setConsentRequired(requiresConsent: boolean): Promise<void>;
}
OneSignal API
See the official OneSignal WebSDK reference for information on all available SDK functions.
Updated about 2 months ago