gapi is not defined - Google sign in issue with gapi.auth2.init gapi is not defined - Google sign in issue with gapi.auth2.init javascript javascript

gapi is not defined - Google sign in issue with gapi.auth2.init


It happens because you have async and defer attributes on your script tag. gapi would be loaded after your script tag with gapi.auth2.init...

To wait for gapi before executing this code you can use onload query param in script tag, like following:

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer></script><script>window.onLoadCallback = function(){  gapi.auth2.init({      client_id: 'filler_text_for_client_id.apps.googleusercontent.com'    });}</script>

Or for case when you need it in many places, you can use promises to better structure it:

// promise that would be resolved when gapi would be loadedvar gapiPromise = (function(){  var deferred = $.Deferred();  window.onLoadCallback = function(){    deferred.resolve(gapi);  };  return deferred.promise()}());var authInited = gapiPromise.then(function(){  gapi.auth2.init({      client_id: 'filler_text_for_client_id.apps.googleusercontent.com'    });})$('#btn').click(function(){  gapiPromise.then(function(){    // will be executed after gapi is loaded  });  authInited.then(function(){    // will be executed after gapi is loaded, and gapi.auth2.init was called  });});


I think you'll find with the above example that this won't work either, as gapi.auth2 will not yet be defined (I know this because I made the same mistake myself, today) You first need to call gapi.load('auth2', callback) and pass THAT a callback which then calls gapi.auth2.init. Here is an example of my _onGoogleLoad function, which is the callback for loading the first platform.js script.

var _auth2var _onGoogleLoad = function () {  gapi.load('auth2', function () {    _auth2 = gapi.auth2.init({      client_id: 'OUR_REAL_ID_GOES_HERE',      scope: 'email',      fetch_basic_profile: false    })    _enableGoogleButton()  })}

After that, you can use the _auth2 variable to actually sign users in.


The problem is not only in gapi. To call init method - auth2 object must be initialized.There is a promise once a google auth object is in fully initialized GoogleAuth.then(onInit, onFailure)

gapi.load('auth2', initSigninV2);function initSigninV2() {    gapi.auth2.init({        client_id: 'CLIENT_ID.apps.googleusercontent.com'    }).then(function (authInstance) {        // now auth2 is fully initialized    });}