Onesignal Integration with Next.js PWA

Written By: Bishakh Neogi
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
Once upon a time, in the land of CosX, a developer was tasked with integrating OneSignal into their Next.js PWA.
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-onesignal
Chapter 3: Configure OneSignal in Your Application
Create a file named runOneSignal.js
in the /public
directory
import OneSignal from 'react-onesignal';
const runOneSignal = async () => {
await OneSignal.init({
appId: 'YOUR_ONESIGNAL_APP_ID',
allowLocalhostAsSecureOrigin: true
});
OneSignal.showSlidedownPrompt();
};
export default runOneSignal;
Chapter 4: Include OneSignal initialization
Update your _app.tsx
to include OneSignal initialization
import "@mantine/core/styles.css";
import { Inter } from "next/font/google";
import { Toaster } from "sonner";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { wagmiClient } from "@/blockchain/config";
import { WagmiProvider } from "wagmi";
import localfont from "next/font/local";
import "@/styles/globals.css";
import { theme } from "@/theme";
import { MantineProvider } from "@mantine/core";
import type { AppProps } from "next/app";
import Head from "next/head";
import { GoogleAnalytics } from "@next/third-parties/google";
import { AppQueryClientProvider } from "@/providers/QueryClientProvider";
import AppWrapper from "@/components/loan/AppWrapper";
import Script from "next/script";
import { useEffect } from "react";
import runOneSignal from "@/public/runOneSignal";
export const inter = Inter({ subsets: ["latin"] });
const generalSans = localfont({
src: [
{
path: "../public/fonts/GeneralSans-Medium.otf",
weight: "500",
style: "medium",
},
{
path: "../public/fonts/GeneralSans-Semibold.otf",
weight: "600",
style: "semibold",
},
],
});
export default function App({ Component, pageProps }: AppProps) {
useEffect(() => {
runOneSignal();
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/OneSignalSDKWorker.js", { scope: "/onesignal/" })
.then(function (registration) {
console.log(
"Service Worker registration successful with scope: ",
registration.scope
);
})
.catch(function (err) {
console.log("Service Worker registration failed: ", err);
});
}
if ("serviceWorker" in navigator) {
navigator.serviceWorker.getRegistrations().then(function (registrations) {
for (let registration of registrations) {
if (registration.active?.scriptURL.includes("sw.js")) {
registration.unregister();
}
}
});
}
}, []);
return (
<MantineProvider theme={theme}>
<Head>
<title>MicroCredit</title>
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, user-scalable=no"
/>
<link rel="shortcut icon" href="/favicon.svg" />
<link rel="manifest" href="/manifest.json" />
</Head>
<Script src="https://cdn.smileidentity.com/inline/v1/js/script.min.js" />
<WagmiProvider config={wagmiClient}>
<AppQueryClientProvider>
<AppWrapper>
<main className={`${generalSans.className} mx-auto`}>
<Component {...pageProps} />
</main>
</AppWrapper>
<ReactQueryDevtools initialIsOpen={false} />
</AppQueryClientProvider>
</WagmiProvider>
</MantineProvider>
);
}
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:
if ("serviceWorker" in navigator) {
navigator.serviceWorker.getRegistrations().then(function (registrations) {
for (let registration of registrations) {
if (registration.active?.scriptURL.includes("sw.js")) {
registration.unregister();
}
}
});
}
What is Service Worker?
1.Interception and Caching: The service worker intercepts network requests, allowing your app to cache resources and provide a faster, offline experience.
2.Background Sync: It enables background synchronization, ensuring that tasks like sending data to the server can continue even when the user is offline.
3.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.
Jo dikhta hai, wahi bikta hai! Yeh integration mein bhi bada mazaa aata hai! Isliye push-notification se paise double apka company ka!!