1

I'm using React with create-react-app and I have integrated Firebase Messaging for push notifications, it requires that you create a file in the public folder firebase-messaging-sw.js that is responsible to setup the service worker with firebase messaging to enable it.

It all works properly, my problem is using the firebase configuration keys directly into code, I know they're public keys, it is still really bad practice to hardcode them plus I have more than one environment (different firebaseConfigs) so it's even more frustating to keep them hardcoded.

The firebase-messaging-sw.js looks like this:

importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');

const firebaseConfig = {
    apiKey: 'example',
    authDomain: 'example',
    databaseURL: 'example',
    projectId: 'example',
    storageBucket: 'example',
    messagingSenderId: 'example',
    appId: 'example',
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (message) {  
    return self.registration.showNotification(
        "Title",
        "Message"
    );
});

I've seen other questions like this How to use process.env in a React service worker

The solutions won't work, the cra-append-sw lib results in babel and webpack errors (those other libs are handled by CRA, so I don't mess with them)

My react-scripts version is 4.0.3

1 Answers1

0

I don't have an actual answer, but I ran into the same problem and what I've been trying is to use the getToken() function. If you take a look to the docs, you can use the optional parameter ServiceWorkerRegistration to set a custom service worker.

const swRegistration = await navigator.serviceWorker.register('/src/firebase-messaging-sw.js');
const token = await fcm.getToken({
      serviceWorkerRegistration: swRegistration,
    });

Now the service worker can live inside the src directory, where it will be built and you can use env variables there. The thing is that if do it this way, I get a mimetype error when registering the service worker. You can see why this error ocurrs in the last answer of this question. Maybe you can build up from this and find a solution, good luck!

General Grievance
  • 4,555
  • 31
  • 31
  • 45