Search code examples
reactjsfirebasefirebase-cloud-messagingreact-ssrrazzle

How to fix self is not defined when firebase messaging method called in react ssr app?


I am trying to use firebase massaging in my SSR app which is created using https://github.com/jaredpalmer/razzle with-react-router-3. I am already using firebase which works great including hosting. But started throwing an error when I started adding messaging in the app.

My entry point looks like,

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/storage';
import 'firebase/firestore';
import 'firebase/messaging';

import FirebaseConfig from 'config/firebase-config.json';
if (!firebase.apps.length) {
  firebase.initializeApp(FirebaseConfig);
}
const messaging = firebase.messaging();

I am getting the bellow error when I start the server with razzle start

/Users/subkundu/Desktop/Work/Projects/React/ownerstown/node_modules/@firebase/messaging/index.ts:75
  if (self && 'ServiceWorkerGlobalScope' in self) {
  ^

ReferenceError: self is not defined

How do I fix it? Any lead will be amazing. Thanks. :)


Solution

  • I believe that you have to provide a check to see if the window is available.

    let Messaging;
    if (YOUR_CHECK_HERE) {
        Messaging = firebase.messaging();
    }
    // Then you can use "Messaging"
    

    I'm not familiar with razzle. Accessing the window varies depending on Server Side Rendering (SSR) frameworks. I got the idea from this post. When I ran into this problem with nuxt.js I was able to check for the window with this process.browser. Hope this helps!