Skip to content

Instantly share code, notes, and snippets.

@statico
Last active April 23, 2021 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statico/c6079ed28e032717a0c9bde85518dee8 to your computer and use it in GitHub Desktop.
Save statico/c6079ed28e032717a0c9bde85518dee8 to your computer and use it in GitHub Desktop.
useOneSignal hook for OneSignal and Next.js with SSR
import getConfig from "next/config"
// Add publicRuntimeConfig: { oneSignalAppId: ... } to next.config.js
const { publicRuntimeConfig } = getConfig()
export const useOneSignal = (externalUserId?: string): void => {
// react-onsignal tries to use a global `document` variable, so we can only
// use it in the client side. Luckily this method doesn't trigger any "wrong
// number of hooks" errors either.
if (!process.browser) return
const module = require("react-onesignal")
const OneSignal = module.default
const { useOneSignalSetup } = module
const oneSignalAppId = publicRuntimeConfig?.oneSignalAppId
OneSignal.initialize(oneSignalAppId, {
allowLocalhostAsSecureOrigin: process.env.NODE_ENV !== "production",
})
useOneSignalSetup(() => {
// This check has to be done within the useOneSignalSetup hook's
// callback, otherwise you'll get "wrong number of hooks" errors.
if (!externalUserId) return
OneSignal.setExternalUserId(externalUserId)
OneSignal.registerForPushNotifications()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment