nuxt-community / firebase-module

🔥 Easily integrate Firebase into your Nuxt project. 🔥
https://firebase.nuxtjs.org
MIT License
641 stars 98 forks source link

Error registering workbox #376

Closed yalondpsi closed 3 years ago

yalondpsi commented 3 years ago

Hi I get: Error registering workbox: TypeError: Cannot read property 'addEventListener' of undefined

workbox.js?8a5e:1 Error registering workbox: TypeError: Cannot read property 'addEventListener' of undefined at new Workbox (workbox-window.dev.es5.mjs?f82d:612) at _callee$ (workbox.js?8a5e:1) at tryCatch (runtime.js?96cf:63) at Generator.invoke [as _invoke] (runtime.js?96cf:293) at Generator.eval [as next] (runtime.js?96cf:118) at asyncGeneratorStep (asyncToGenerator.js?1c17:3) at _next (asyncToGenerator.js?1c17:25)

Do you need more info beyond that? Thanks Yalon

lupas commented 3 years ago

Hey @yalondpsi

This error is from workbox and does not necessarily have to come from this module... Could you share your nuxt.config.js and your package.json?

yalondpsi commented 3 years ago

Hey @lupas Here are the content of those files. (I just deleted the firebase.config values) Thanks

package.json:

{
  "name": "",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt --hostname 10.100.102.15 --port 3333",
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.32",
    "@fortawesome/free-brands-svg-icons": "^5.15.1",
    "@fortawesome/free-solid-svg-icons": "^5.15.1",
    "@fortawesome/vue-fontawesome": "^2.0.0",
    "@nuxtjs/axios": "^5.12.2",
    "@nuxtjs/firebase": "^7.1.0",
    "@nuxtjs/pwa": "^3.2.2",
    "ace-builds": "^1.4.12",
    "cookie": "^0.4.1",
    "cookieparser": "^0.1.0",
    "express": "^4.17.1",
    "firebase": "^8.0.1",
    "firebase-admin": "^9.3.0",
    "firebase-functions": "^3.11.0",
    "jquery": "^3.5.1",
    "js-cookie": "^2.2.1",
    "lodash": "^4.17.19",
    "nuxt": "^2.14.7",
    "storyblok-nuxt": "^1.3.0",
    "vue-sweetalert2": "^3.0.8",
    "webpack": "^4.44.1"
  },
  "devDependencies": {
    "@nuxtjs/fontawesome": "^1.1.2",
    "@nuxtjs/vuetify": "^1.11.2"
  }
}

nuxt.config:

const webpack = require('webpack');
import colors  from 'vuetify/es5/util/colors';

//export default {
module.exports = {
  target: 'server',

  head: {
    titleTemplate: '%s - ' + process.env.npm_package_name,
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [ 
    ],
  },
  loading: { color: '#8028A6', height: '4px' },

  pageTransition: {
    css: false
  },
  /*
  ** Global CSS
  */
  css: [
    '~/static/css/google.css',
    '~/static/css/main.css',
    ],
    router: {
      middleware: 'testMiddleware'
    },

    plugins: [
    ],

  components: true,
  buildModules: [
    //! https://go.nuxtjs.dev/vuetify
    '@nuxtjs/vuetify',
    //! https://github.com/nuxt-community/fontawesome-module
    '@nuxtjs/fontawesome'
  ],

  fontawesome: {
    component: 'fa', //! the name of font prefix
    icons: {
      solid: ['faCog', 'faCaretDown', 'faCircleNotch', 'faEnvelope', 'faLock', 'faEye', 'faEyeSlash', 'faExclamationCircle', 
              'faCrown', 'faGamepad', 'faIdCard', 'faTrophy', 'faStore', 'faQuestionCircle',
              'faChevronCircleLeft', 'faChevronCircleRight',
              'faEllipsisV',
              'faPlay',
              'faCubes', 'faImages', 'faSlidersH', 'faPlusCircle', 'faTimesCircle'
            ], //! custom fonts loading 
      // brands: ['faGoogle']
    }
  },

  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/firebase',
    [
      'storyblok-nuxt',
      {
        accessToken: process.env.SB_TOKEN,
        cacheProvider: 'memory'
      }
    ],
    ['vue-sweetalert2/nuxt',
      {
        customClass:{title: 'title-class'}, //! title-class declared in main.css
        background: '#1C2541',
        confirmButtonColor: '#059FDB',
        cancelButtonColor: '#ff7674'
      }
    ],

  ],
  axios: {
    // retry: { retries: 3 }
  },

  firebase: {
    lazy: false,
    config: {
      apiKey: '',
      authDomain: '',
      databaseURL: '',
      projectId: '',
      storageBucket: '',
      messagingSenderId: '',
      appId: '',
      measurementId: '',
      fcmPublicVapidKey:
        '',
    },
    onFirebaseHosting: true,
    services: {
      auth: {
        persistence: 'local', // default
        initialize: {
          onAuthStateChangedAction: 'onAuthStateChanged',
        },
        ssr: true,
      },
      firestore: {
        memoryOnly: false,
        emulatorPort: false,

      },
      functions: true,
      storage: false,
      database: false,
      performance: false,
      analytics: false,

      /*
      remoteConfig: {
        settings: {
          fetchTimeoutMillis: 60000,
          minimumFetchIntervalMillis: 43200000,
        },
        defaultConfig: {
          welcome_message: 'Welcome',
        },
      },
      */
      /*
      messaging: {
        createServiceWorker: true,
        actions: [
          {
            action: 'goToUrl',
            url: 'https://github.com/lupas',
          },
        ],
      },
      */
    },
  },

  pwa: {
    // disable the modules you don't need
    meta: false,
    icon: false,

    workbox: {
      dev: process.env.NODE_ENV === 'development',
      importScripts: [
        'static/firebase-auth-sw.js'
      ],
    }
  },

  vuetify: { 
    treeShake: false,
    defaultAssets: {
      font: false,
      icons: 'mdiSvg', 
    },
    theme: {
      dark: true,
      rtl:false,

      themes: {
        light: {
          primary: colors.orange.darken2,
          secondary: '#0b132b',
          accent: '#82B1FF',
          error: '#FF5252',
          info: '#2196F3',
          success: '#4CAF50',
          warning: '#FB8C00',
          background: '#ffffff',

        },
        dark: {
          primary: colors.orange.darken2,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.red.accent4,
          success: colors.green.accent3,
          background: '#FF5722', /* deep-orange*/   /* old: #EE5514*/

        }
      }
    }
  },

  buildDir:'../functions/.nuxt', 
  build: {
    // vendor: ['vuetify'],
    extractCSS: true,
    transpile: [],
    plugins: [ //todo: remove jquery
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        _: 'lodash'
      })
    ],
    extend(config, ctx) {
        if (ctx.isClient) {
          config.optimization.splitChunks.maxSize = 200000
        }

      // determine publicPath according the eviroment
      if (ctx.isDev){
        config.output.publicPath = '/_nuxt/'; 
      }else {
        config.output.publicPath = '/_nuxt/'; 
      }
    },
    babel: { compact: true } 
  },
  publicRuntimeConfig: {
   },
  privateRuntimeConfig: {
  },
}
yalondpsi commented 3 years ago

@lupas Hi, Any news?

lupas commented 3 years ago

Hey @yalondpsi

Thanks for the sponsoring - appreciate it :)

Not sure if that is the only issue, but your importScripts in the pwa-workbox config of nuxt.config.js should look like this imho:

importScripts: [
        'firebase-auth-sw.js'
      ],

Can you check if that fixes the issue? If not, could you check:

If any of this does get rid of the error we might find out where the issue lies...

br, Pascal

yalondpsi commented 3 years ago

@lupas Hi, I will try your suggestions and let you know Thanks Yalon

yalondpsi commented 3 years ago

Hi @lupas, When I disabled the pwa module the error did not appear. But, the most valuable feature I need for my project is the ability to have firebase auth working with persistence LOCAL so when the user refreshes the page or close the browser - it's logged in status remains. As you saw probably this is an SSR app and your great module solves this problem as I saw when downloaded your demo app (few days ago - before your last commit)

Thanks Yalon

yalondpsi commented 3 years ago

BTW @lupas, If you think that an online session between us (that way I can share my screen), will help you to understand the problem quickly - I will gladly send you a link on a schedule you find convenient.

yalondpsi commented 3 years ago

@lupas I think I found the problem

It has something to do with definition of IP at the package.json I have more slim nuxt app I made just for testing with your example app. When I change to nuxt --hostname 10.100.102.15 I got at the test app the same error. (http://10.100.102.15:3020/) When I removed the ip definision (http://localhost:3020/) - the error gone. This is for the TEST app

Regarding my Main app - I change it to http://localhost:3333/ Now I've got new error regarding the imports of firebase: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:3333/__/firebase/8.0.1/firebase-app.js' failed to load.

What are your suggestions please? Thanks Yalon

yalondpsi commented 3 years ago

@lupas Hi again :) When I change onFirebaseHosting to false the error gone and the Service worker successfully installed. The problem is that I am using firebase hosting.. Thanks Yalon

lupas commented 3 years ago

Hey @yalondpsi

I can reproduce the issue locally when setting onFirebaseHosting to true myself. So I think you find the issue! 👏👏👏

To quickly fix your issue: You can simply delete onFirebaseHosting or set it to false and your code should run fine. It's not a big performance difference anyway.

All this flag does is import the Firebase scripts from Firebase hosting directly instead of from www.gstatic.com, if it is deployed on Firebase hosting:

<% if (options.onFirebaseHosting) { %>
// Only works on Firebase hosting!
importScripts('/__/firebase/<%= options.firebaseVersion %>/firebase-app.js')
importScripts('/__/firebase/<%= options.firebaseVersion %>/firebase-auth.js')
importScripts('/__/firebase/init.js')
<% } else { %>
importScripts(
  'https://www.gstatic.com/firebasejs/<%= options.firebaseVersion %>/firebase-app.js'
)
importScripts(
  'https://www.gstatic.com/firebasejs/<%= options.firebaseVersion %>/firebase-auth.js'
)
firebase.initializeApp(<%= serialize(options.config) %>)
<% } %>

This does obviously not work when run on localhost, since you don't provide the Firebase SDK with the nuxt dev server. But it should work after you deploy it to Firebase hosting or if you run your code locally with the emulator like so firebase serve --only hosting

Does this make sense? Let me know if it works!

I will think about:

yalondpsi commented 3 years ago

Hi @lupas I will make some tests and deploying and let you know of course. Regarding the IP at package.json (nuxt --hostname xx.xxx.xxx.xx) - this is a nuxt bug? Thanks

lupas commented 3 years ago

Hey @yalondpsi

Alright, let me know if the above does not work.

About the --hostname issue: I get the same issue on dev even when completely removing @nuxtjs/firebase and only using the PWA workbox module together with --hostname, so it seems to me as if this is an issue with workbox or the PWA module itself.

See this simple repo: https://github.com/lupas/lupas-temp/tree/nuxt-pwa-hostname-issue

Might need to open an issue at the pwa module for this.

yalondpsi commented 3 years ago

Hi @lupas, I'm still testing :)

I changed the onFirebaseHosting to: onFirebaseHosting: process.env.NODE_ENV === 'development'? false:true, for performance sake I guess it better to have firebase imports from firebase server on production

Regarding the --hostname issue: I'm glad you found the problem! I think you should to open an issue (or you want me to do this?) because it is very inconvenient to develop without that option available.

yalondpsi commented 3 years ago

@lupas Hi, You updated the demo app of your module to : https://nuxt-fire-demo.firebaseapp.com (firebase hosting) I think you forgot to update the old links (they are still pointing to https://nuxt-fire-demo.herokuapp.com/ ) - which isn't working

one dead link is at https://firebase.nuxtjs.org/community/demo/ and the other one is at: https://github.com/lupas/nuxt-firebase-demo

lupas commented 3 years ago

@yalondpsi

About the demo app It's supposed to be https://nuxt-fire-demo.herokuapp.com/, the link on the readme was wrong and there was a small bug that I just fixed. Thanks for letting me know!

About the hostname issue I never use --hostname myself, so I would have to take a closer look at it first before opening an issue. I might do that but don't think I will find the time in the next few days. If you need it fixed quickly I think it's better if you open an issue yourself.

Maybe I ask - Why is it inconvenient without this option? I can't really find a usecase where I would need that option for local development - what exactly is your use case?

yalondpsi commented 3 years ago

@lupas About the hostname I can wait few more days for you to look into it. no problem.

The advantage of pointing the browser to an IP and not to localhost is: On the same WIFI network I can test the app with different physical computers and phones - by pointing them to that IP. Also, I made my development computer to have a static IP so even when I restart it, it still have the same address.

*If you need my help with that please let me know

yalondpsi commented 3 years ago

@lupas I have a question :) Do you recommend to host nuxt app on heroku over firebase hosting?

lupas commented 3 years ago

Hey @yalondpsi

Initial issue Created this "todo" issue for myself so I can improve this when I find time: https://github.com/nuxt-community/firebase-module/issues/379

Did the initial problem from this issue get solved? In that case I would close this issue, because I wanna don't mix several problems in one issue. If you have new issues or questions you can always open a new issue :-)

Workbox issue Found time to create an issue on the pwa-module repo here: https://github.com/nuxt-community/pwa-module/issues/394. Please follow the progress there.

About Firebase vs Heroku: I generally use target: static and deploy 99% of my apps, even Firebase apps, to Netlify. I prefer it much over Firebase Hosting. The demo app I deployed to Heroku because I wanted to showcase it on a NodeJS hosting so I can show the ssr: true auth working, which is not possible on a static app. Firebase Hosting is static hosting. There is a way using Firebase functions, but yeah... not my kinda thing.

Thanks for all your input & findings - appreciate it!

br, Pascal

yalondpsi commented 3 years ago

Hi @lupas , Thank you for this wonderful module!!! As you suggested I'm closing this issue. Bye for now Yalon