I'm developing a gatsby-pwa with inbuilt fcm. As I'm trying to initialize the messaging instance in my firebase.js file, I receive the error WebpackError: ReferenceError: IDBIndex is not defined.
//firebase.js
import app from "gatsby-plugin-firebase-v9.0"
import { getFirestore } from "firebase/firestore";
import { getMessaging } from "firebase/messaging"
export const db = getFirestore(app);
export const messaging = getMessaging(app);
Interestingly enough, if I create a comment around the messaging const, I can build without problems or warnings. How can this happen if it doesn't happen with the db const as this is initialized perfectly?
Kind regards
Tom
This is a common issue with Firebase (and others third-party modules) and the cause of the issue is the SSR (Server-Side Rendering). Where the code is being compiled in the Node server but targeting the web (using window or other generated global objects).
You can bypass this issue by adding the following snippet in the gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
actions,
getConfig
}) => {
if (stage === 'build-html') {
actions.setWebpackConfig({
externals: getConfig().externals.concat(function(context, request, callback) {
const regex = /^@?firebase(\/(.+))?/;
if (regex.test(request)) {
return callback(null, 'umd ' + request);
}
callback();
})
});
}
};
Basically, this is excluding firebase from being bundled so they will be loaded by the client in the runtime, as it is requested.
Following the same approach, you can lazy-load or dynamically import Firebase with:
import('firebase').then(firebase => {
firebase.initializeApp({ /* firebaseConfig goes here */});
firebase.firestore().collection('someCollection').doc('someID').get()
.then(doc => {
// do stuff with Firestore data
});
});
Have you considered using any service-worker like gatsby-plugin-firebase-messaging.
Following your approach, it seems to be needed to handle Firebase message responses object like:
const messaging = firebase.messaging();
Source: https://github.com/gatsbyjs/gatsby/discussions/27726