javascriptflutterfirebasefirebase-cloud-messaging

How to choose the correct Firebase JS SDK version for firebase-messaging-sw.js in a Flutter Web app?


I have a Flutter/Firebase web app where I am trying to add firebase cloud messaging (notifications).

Part of this setup is to create a service worker file "firebase-messaging-sw.js", with example contents:

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

firebase.initializeApp({
  apiKey: "YOUR_API_KEY",
  authDomain: "your-app.firebaseapp.com",
  projectId: "your-app",
  storageBucket: "your-app.appspot.com",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
});

const messaging = firebase.messaging(); 

But how am I supposed to know what exact version (other than 10.3.0) that I should be using?

I assume it relates to the version of firebase messaging in my pubspec.yaml... and that there is a some matrix somewhere online but I cant find it. I keep going in circles through docs, youtube videos, and chat gpt.

There is this doc with a note:

// Please see this file for the latest firebase-js-sdk version: // https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core_web/lib/src/firebase_sdk_version.dart

... but that just tells you the latest version, not the version that matches your project... so I'm nervous to use it... or is it always backward compatible?


Solution

  • The contents of firebase-messaging-sw.js are spelled out in the Firebase documentation here.

    For example it currently is:

    // Please see this file for the latest firebase-js-sdk version:
    // https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core_web/lib/src/firebase_sdk_version.dart
    importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js");
    importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js");
    
    firebase.initializeApp({
      apiKey: "...",
      authDomain: "...",
      databaseURL: "...",
      projectId: "...",
      storageBucket: "...",
      messagingSenderId: "...",
      appId: "...",
    });
    
    const messaging = firebase.messaging();
    
    // Optional:
    messaging.onBackgroundMessage((message) => {
      console.log("onBackgroundMessage", message);
    });
    

    Which is aside from version numbers the same as the code for version 10.3.0 in your question. All this really does is wire up the firebase.messaging.onBackgroundMessage callback with some configuration data.

    I'm pretty sure the service worker code hasn't change for about a decade or so, so you should be fine using it as is.

    Even if the service worker code and API it depends on were to change in the future, you're pinning the version in those importScripts calls - so existing deploys will continue to work fine.