To fix ‘gapi is not defined’ error with JavaScript Google sign in, we should make sure the auth2 object is initialized before calling init.
For instance, we write
const initSigninV2 = async () => {
const authInstance = await gapi.auth2.init({
client_id: "CLIENT_ID.apps.googleusercontent.com",
});
//...
};
gapi.load("auth2", initSigninV2);
to call init in the initSigninV2 function.
init returns a promise with the auth object.
And then we make sure initSigninV2 is called only after the auth2 object is loaded by calling load with 'auth2' and initSigninV2 as its callback.