Next.js Discord

Discord Forum

How integrate OneSignal for push notification ?

Unanswered
California pilchard posted this in #help-forum
Open in Discord
Avatar
California pilchardOP
Everything is in the title. I have a NextJS web app with PWA support and I wanna have push notification with OneSignal. But how we do that ? I have this start :
// next.config.js
const withPWA = require('@ducanh2912/next-pwa').default({
  dest: 'public',
  customWorkerSrc: 'service-worker',
  register: true,
  skipWaiting: true,
  // disable: process.env.NODE_ENV === 'development',
});

And inside /service-worker/index.js :
importScripts("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js");

I also have a Context with this :
export const OneSignalContext = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const { user } = useAuth();

  const [oneSignalInitialized, setOneSignalInitialized] =
    useState<boolean>(false);

  /**
   * Initializes OneSignal SDK for a given Supabase User ID
   * @param uid Supabase User ID
   */
  const initializeOneSignal = async (uid: string) => {
    if (oneSignalInitialized) {
      return;
    }
    setOneSignalInitialized(true);
    await OneSignal.init({
      appId: process.env.NEXT_PUBLIC_ONESIGNAL_APP_ID!,
      safari_web_id: process.env.NEXT_PUBLIC_ONESIGNAL_SAFARI_WEB_ID,
      notifyButton: {
          enable: true,
      },
      allowLocalhostAsSecureOrigin: true,
    });
    await OneSignal.login(uid);
    OneSignal.Slidedown.promptPush();
  };

  useEffect(() => {
    user && initializeOneSignal(user.id);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user]);

  return (
    <>
      <script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer />
      {children}
    </>
  );
};

But the first prompt never show

0 Replies