A step-by-step guide to integrating OneSignal push notifications into a Next.js Progressive Web Application, handling multiple service workers and cross-browser compatibility.
Problem Statement
In today's fast-paced digital world, ensuring timely and engaging communication with users is paramount for any web application. Push notifications have become a vital tool in achieving this goal. However, integrating push notification services like OneSignal with a Next.js Progressive Web Application (PWA) can be daunting, especially when dealing with multiple service workers and ensuring seamless compatibility across various devices and browsers. This guide aims to simplify the integration process, providing a step-by-step approach to successfully implement OneSignal in a Next.js PWA application, while addressing common challenges and errors, such as handling multiple service workers.
In a world where notifications are king, ensuring that your application can keep users informed and engaged is paramount. But fear not! We're here to demystify the process and guide you through the integration, one step at a time.
Imagine your PWA as a bustling city. OneSignal is the postal service, ensuring every message reaches its intended recipient. The service worker is the diligent postman, tirelessly delivering notifications. And your Next.js application? It's the vibrant city that keeps growing and evolving.
Chapter 1: Setting Up the Scene
The goal? To send timely push notifications to users and keep them engaged. The developer knew this would be a challenging task, but with determination and a bit of humor, they set off on their quest.
Chapter 2: Install OneSignal
Install the OneSignal package using yarn:
yarn add react-onesignalChapter 3: Configure OneSignal in Your Application
Create a file named onesignal.js in the public directory.
import OneSignal from 'react-onesignal';
const notificationConfig = async () => {
await OneSignal.init({
appId: 'YOUR_APP_ID_HERE',
// safari_web_id: "YOUR_SAFARI_WEB_ID",
allowLocalhostAsSecureOrigin: true,
});
OneSignal.showNativePrompt();
};
export default notificationConfig;Chapter 4: Include OneSignal Initialization
Update your _app.tsx to include OneSignal initialization and service worker registration.
import type { AppProps } from 'next/app';
import { useEffect } from 'react';
import notificationConfig from '../public/onesignal';
export default function MyApp({ Component, pageProps }: AppProps) {
useEffect(() => {
// Initialize OneSignal
notificationConfig();
// Register OneSignal service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/OneSignalSDKWorker.js', { scope: '/onesignal' })
.then((registration) => {
console.log('OneSignal SW registered with scope:', registration.scope);
})
.catch((err) => {
console.log('OneSignal SW registration failed:', err);
});
}
// Register your app's own service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then((registration) => {
registration.active?.postMessage({ type: 'INIT' });
})
.catch((err) => {
console.error('App SW registration failed:', err);
});
}
}, []);
return (
<>
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no, user-scalable=no, viewport-fit=cover"
/>
<link rel="manifest" href="/manifest.json" crossOrigin="anonymous" />
<Component {...pageProps} />
</>
);
}5. Service Worker: OneSignalSDKWorker.js
Copy the OneSignal service worker file into the public directory. You can get this file from the OneSignal setup documentation.
The service worker is crucial in enabling push notifications for your PWA. It acts as a background worker that intercepts network requests, caches resources, and manages push notifications. In our OneSignal integration, the service worker ensures that notifications are received even when the app is not actively being used.
6. Handling Multiple Service Workers
If you already have multiple service workers, you must ensure they don't conflict. In your _app.tsx, handle existing service workers:
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/OneSignalSDKWorker.js', { scope: '/onesignal' })
.then((registration) => {
console.log('Service Worker registration successful with scope:', registration.scope);
})
.catch((err) => {
console.log('Service Worker Registration failed:', err);
});
// Handle existing registrations
navigator.serviceWorker.getRegistrations().then((registrations) => {
for (const registration of registrations) {
if (registration.active?.scriptURL.includes('sw.js')) {
registration.active.postMessage({ type: 'js' });
}
}
});
}
}, []);What is Service Worker?
- Interception and Caching: The service worker intercepts network requests, allowing your app to cache resources and provide a faster, offline experience.
- Background Sync: It enables background synchronization, ensuring that tasks like sending data to the server can continue even when the user is offline.
- Push Notifications: The service worker listens for push events, enabling your app to receive and display notifications even when it is not active. This is crucial for keeping users engaged and informed.
Pro tip: Always test your service worker registration in an incognito window to avoid cached states interfering with your integration. Use Chrome DevTools → Application → Service Workers to monitor registrations in real time.
Ready to Scale with AI?
Join forward-thinking teams already working with CosX AI. Tell us your challenge and we'll map the highest-value workflows to automate first.
Written by
Engineering
Published
October 22, 2024
Duration
6 min read
Share
Tags


