firebase / firebase-js-sdk

Firebase Javascript SDK
https://firebase.google.com/docs/web/setup
Other
4.84k stars 889 forks source link

Firebase Cloud Messaging (FCM) fails to retrieve token on mobile (PWA), works fine on web. #8592

Open MahmoudAdel9 opened 3 days ago

MahmoudAdel9 commented 3 days ago

Operating System

Android 10

Environment (if applicable)

Chrome on desktop and PWA on mobile

Firebase SDK Version

0.10.13

Firebase SDK Product(s)

Messaging

Project Tooling

Next js app

Detailed Problem Description

When attempting to use Firebase Cloud Messaging (FCM) on a Progressive Web App (PWA), the service works fine on web (desktop browsers). However, on mobile browsers, the FCM token is not being generated and registrations POST request return 401 with this message:

Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential

WhatsApp Image 2024-10-23 at 21 31 59_82436527

Observed behavior

On desktop browsers (Chrome), everything works as expected: the FCM token is retrieved and notifications can be sent. On mobile browsers (tested on Chrome for Android), the getToken function does not return a token. The service worker registers successfully on both desktop and mobile.

Steps and code to reproduce issue

'use client'; import firebaseApp from '@/firebase'; import { getMessaging, getToken } from 'firebase/messaging'; import { useEffect, useState } from 'react';

const useFcmToken = () => { const [token, setToken] = useState(''); const [notificationPermissionStatus, setNotificationPermissionStatus] = useState('');

useEffect(() => { const retrieveToken = async () => { try { if (typeof window !== 'undefined' && 'serviceWorker' in navigator) { const registration = await navigator.serviceWorker.register( '/firebase-messaging-sw.js' ); console.log('Service worker registered:', registration); console.log('firebaseApp', firebaseApp);

      const messaging = getMessaging(firebaseApp);

      console.log(messaging, 'TOKENmessagingTOKEN');

      // Request notification permission
      const permission = await Notification.requestPermission();

      setNotificationPermissionStatus(permission);

      if (permission === 'granted') {
        console.log('permission is <<<<<<granted>>>>>>>>>');

        const currentToken = await getToken(messaging, {
          vapidKey: process.env.VAPID_KEY
        });

        console.log(currentToken, 'currentTokencurrentToken');

        if (currentToken) {
          setToken(currentToken);
        } else {
          console.log(
            'No registration token available. Request permission to generate one.'
          );
        }
      }
    }
  } catch (error) {
    console.log('Error retrieving token:', error);
  }
};

retrieveToken();

}, []);

return { fcmToken: token, notificationPermissionStatus }; };

export default useFcmToken;

return { fcmToken: token, notificationPermissionStatus }; };

export default useFcmToken;

google-oss-bot commented 3 days ago

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

looptheloop88 commented 2 days ago

Hi @MahmoudAdel9, thanks for patiently waiting. I tried to reproduce the issue using a similar code snippet to the one you provided, but I was unsuccessful. I used the latest version of the JS SDK (11.0.1) and updated version of Chrome browser. I deployed the Next.js web app using Firebase Hosting and able to get FCM tokens upon accessing the site URL on both desktop and mobile Chrome browsers.

I suggest you check the following pointers and see if it can help you resolve the issue:

I also noticed that the FCM token generation took approximately 3 to 5 seconds. I am not sure if it's just the speed of my network connection, but I tried this multiple times and the FCM token is getting generated successfully.