firebase-js-sdk icon indicating copy to clipboard operation
firebase-js-sdk copied to clipboard

Cannot read property 'navigator' of undefined

Open tcaer opened this issue 8 years ago • 15 comments

[REQUIRED] Describe your environment

  • Operating System version: Mac OS Mojave
  • Browser version: Chrome Canary
  • Firebase SDK version: Latest 5,4,1
  • Firebase Product: all

[REQUIRED] Describe the problem

Steps to reproduce:

When I try to initialize firebase I can error in chrome:

auth.esm.js:10 Uncaught TypeError: Cannot read property 'navigator' of undefined
    at auth.esm.js:10
    at Object.<anonymous> (auth.esm.js:315)
    at Object../node_modules/@firebase/auth/dist/auth.esm.js (main.bundle.js:11217)
    at __webpack_require__ (bootstrap:723)
    at fn (bootstrap:100)
    at Object../node_modules/firebase/dist/index.cjs.js (index.cjs.js:7)
    at __webpack_require__ (bootstrap:723)
    at fn (bootstrap:100)
    at Object../src/app/app.component.tsx (app.component.tsx:4)
    at __webpack_require__ (bootstrap:723)

I am not sure how to fix this, seems to be that when bundling firebase, the code breaks somehow.

Relevant Code:

File where I initialize firebase:

import * as React from 'react';
import { Link, Route } from 'react-router-dom';

import firebase from 'firebase';
import 'firebase/auth';

import { environment } from '../environments/environment.dev';
import { authState } from 'rxfire/auth';

import './app.component.scss';

interface State {
  toggleDropdown: boolean;
}

export class AppComponent extends React.Component<{}, State> {

  user: firebase.User;

  constructor(props: any) {
    super(props);

    this.state = { toggleDropdown: false };

    firebase.initializeApp(environment.firebase);

    this.onAccountToggle = this.onAccountToggle.bind(this);
  }

  componentWillMount(): void {
    authState(firebase.auth()).subscribe(u => (this.user = u));
  }

  onAccountToggle() {
    this.setState({ toggleDropdown: !this.state.toggleDropdown });
  }

  render() {
    let accountToggle;
    if (this.state.toggleDropdown) {
      accountToggle = <div className='account_toggle'>
        <Link to="/account">Account</Link>
        <a>Logout</a>
      </div>
    } else {
      accountToggle = null;
    }

    return <div className='container'>
      <nav className='nav'>
        <div className='container'>
          <div className='links'>
            <Link to="/">Home</Link>
            <Link to="/activity">Activity</Link>
            <Link to="/wallet">Wallet</Link>
            <Link to="/help">Help</Link>
            <a className='account' onClick={this.onAccountToggle}>Account</a>
            {accountToggle}
          </div>
        </div>
      </nav>
      <div>
        { JSON.stringify(this.user) }
      </div>
    </div>
  }
  
}

Webpack:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].bundle.js'
  },
  devtool: 'source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.scss']
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        loader: 'ts-loader'
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: () => ([
                require('autoprefixer'),
                require('precss')
              ])
            }
          }
        ]
      },
      { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') }),
    new webpack.HotModuleReplacementPlugin()
  ]
}

https://stackblitz.com/fork/firebase-issue-sandbox

// TODO(you): code here to reproduce the problem

Thanks for any help.

tcaer avatar Aug 26 '18 04:08 tcaer

Hey there! I couldn't figure out what this issue is about, so I've labeled it for a human to triage. Hang tight.

google-oss-bot avatar Aug 26 '18 04:08 google-oss-bot

Hey @tcaer, does this only happen in version 5.4.1? Can you check previous versions to help us isolate the cause? I have an idea why this may be happening and have a patch to fix it: https://github.com/firebase/firebase-js-sdk/pull/1166

bojeil-google avatar Aug 26 '18 07:08 bojeil-google

Hi, this also happens in version 5.4.0, 5.3.0, and 5.2.0. Perhaps this may also be a problem with webpack? I left my configuration in my original post but it seems weird that so many versions of firebase would be produced with this type of issue in it.

tcaer avatar Aug 26 '18 14:08 tcaer

Hmm, I don't think this is related to Auth. I merged the tweak to the code I mentioned, but I doubt it is related to this. Seems likely related to your webpack setup. Can't really say with the information I have.

bojeil-google avatar Aug 27 '18 16:08 bojeil-google

It may be related to this: https://stackoverflow.com/questions/34973442/how-to-stop-babel-from-transpiling-this-to-undefined

bojeil-google avatar Aug 27 '18 16:08 bojeil-google

I'm having this issue too with Babel preset env.

For the time being going back to 4.12.1 works.

npm remove firebase
npm install [email protected]

PierBover avatar Sep 01 '18 21:09 PierBover

Not sure if it is going to solve the issue, but it is problematic to import both firebase and firebase/auth. firebase package is an all in one package and includes all components including firebase/auth. We encourage developers to include only components they use. You can do the following instead:

import firebase from 'firebase/app'
import 'firebase/auth'

Feiyang1 avatar Sep 27 '18 17:09 Feiyang1

Thanks for the tip, installing [email protected], fixed the issue for me too.

vbmcfarlane avatar Oct 02 '18 21:10 vbmcfarlane

I'm having this issue too with Babel preset env.

For the time being going back to 4.12.1 works.

npm remove firebase
npm install [email protected]

The tip worked and I'm back up and running. Thanks a bunch @PierBover

If anyone has further info as to why this is happening under the hood, and how to arrive at a solution that works with the current version of firebase auth, please share :).
I don't understand how the babel preset env could torpedo the firebase auth module, but would love to learn what is going on here.

TimmDay avatar Oct 03 '18 11:10 TimmDay

@tcaer @TimmDay @PierBover Can you please provide a minimal code/config example that reproduces this issue? I was not able to reproduce it with Babel preset env.

Feiyang1 avatar Oct 03 '18 17:10 Feiyang1

Sure. I can't attest to whether the babel env was the actual perpetrator causing the clash, just that rolling back to [email protected] allowed me to use the 'auth' module again with my current set up.

Here are all the other dependencies in my package.json. It is quite possible that I have missed something obvious.

{
  "name": "factory_display",
  "version": "1.0.7",
  "main": "index.js",
  "author": "Tim Day",
  "license": "MIT",
  "scripts": {
    "build:dev": "webpack",
    "build:prod": "webpack -p --env production",
    "dev-server": "webpack-dev-server",
    "start": "node server/server.js",
    "test": "jest --config=jest.config.json",
    "build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch",
    "heroku-postbuild": "yarn run build:prod"
  },
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "1.5.2",
    "babel-preset-react": "6.24.1",
    "css-loader": "^0.28.11",
    "enzyme-adapter-react-16": "^1.2.0",
    "express": "4.16.0",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "firebase": "4.12.1",
    "moment": "2.18.1",
    "node-sass": "^4.8.3",
    "normalize.css": "^8.0.0",
    "numeral": "2.0.6",
    "raf": "^3.4.0",
    "react": "^16.3.1",
    "react-addons-shallow-compare": "15.6.0",
    "react-dates": "12.7.0",
    "react-dom": "^16.3.1",
    "react-modal": "^3.3.2",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.2.2",
    "redux": "^4.0.0",
    "redux-mock-store": "^1.5.3",
    "redux-thunk": "^2.3.0",
    "sass-loader": "^6.0.7",
    "style-loader": "^0.20.3",
    "uuid": "^3.2.1",
    "validator": "^9.4.1",
    "webpack": "^4.5.0"
  },
  "devDependencies": {
    "enzyme": "^3.4.1",
    "enzyme-to-json": "^3.3.4",
    "jest": "^23.1.0",
    "react-test-renderer": "^16.4.2",
    "webpack-cli": "^2.0.13",
    "webpack-dev-server": "^3.1.3"
  }
}

The issue only happened when I was using the current version of firebase, and require('firebase/auth'); The other firebase modules (I tested database, messaging, functions) all ran without an issue.

TimmDay avatar Oct 05 '18 08:10 TimmDay

I doubt I will have time to create a repro... but here are my babel dependencies:

    "babel-polyfill": "^6.26.0",
    "babel-preset-es2017": "^6.24.1",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-env": "^1.2.1",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",

And my .babelrc:

{
  "presets": [
    ["env", { "modules": false }],
    "es2017",
    "stage-2"
  ],
  "plugins": ["transform-runtime"],
  "comments": false,
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": [ "istanbul" ]
    }
  }
}

This is a Vue project btw, although I doubt that's relevant.

PierBover avatar Oct 05 '18 13:10 PierBover

@TimmDay @PierBover Thank you for the quick response. The problem is the older babel preset env doesn't recognize iife invoked by call correctly and map this to undefined. We have made a fix here: https://github.com/firebase/firebase-js-sdk/pull/1291

Feiyang1 avatar Oct 05 '18 23:10 Feiyang1

As an alternative to waiting for the fix to be released, you can upgrade to babel 7 at the mean time.

Feiyang1 avatar Oct 05 '18 23:10 Feiyang1

I had a similar issue. I was able to resolve it by changing my target from es2015 to es5 in my tsconfig.json file. I hope this can help someone.

johan-lindahl avatar Jul 21 '19 11:07 johan-lindahl