Google APIs Client Library for browser JavaScript, aka gapi.

  • By Google
  • Last update: Dec 29, 2022
  • Comments: 17

Google API Client Library for JavaScript


The Google API Client Library for JavaScript is designed for JavaScript client-application developers. It offers simple, flexible access to many Google APIs.

Note: This repo does not contain the source code for the gapi client.


The JavaScript client library supports these Google APIs.

The library supports OAuth 2 authentication.

If you use TypeScript, you can install @types/gapi for autocompletion.






  • 1

    New cross-site cookie not 'SameSite' warning in Chrome


    I am wondering if anyone else has run into the following warning related to cross-site cookies with the latest version of Chrome. Per the documentation, Chrome version 80 will only deliver cookies set correctly. Is this something that I can fix in my application or something that we need for Google to fix?

    A cookie associated with a cross-site resource at was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at and

    To reproduce above warning, go to google's example sign-in website in chrome 77+ and view the logs the console:

  • 2

    gapi.client.load() failed .. 404 (Not Found)

    From [email protected] on May 22, 2014 21:24:42

    it seems trying to access an url with double '/_ah/api' paths: .

    Original issue:

  • 3

    OAuth2 SignIn error at first time

    Hello everyone!

    I'm working with Google Sign-In JavaScript through Google OAuth2 API:

    var googleAuth = {};
    gapi.load('auth2', function(){
            googleAuth = gapi.auth2.init({ client_id: [MY_CLIENT_ID] });

    When I try to make signing up a user, meaning that he needs to authorize Google to use my app, through signIn() method...

    var options = new gapi.auth2.SigninOptionsBuilder();

    The Promise object that signIn() returns resolves with an error:

    Object {type: "tokenFailed", idpId: "google", error: "IMMEDIATE_FAILED"}

    I checked all reference and I could not found anything about this error. Only about IMMEDIATE_FAILED but it should happen in case API forces user to signin without prompting about authorization using option Prompt: none ( that's what I'm setting Prompt: consent, to ensure that is not related with it ) and user had not given permissions to the application.

    I couldn't even resolve it o find a pattern playing with SignIn options.

    Could anybody help me?

    Thanks! :)

  • 4

    Google Sign-In button doesn't work in Edge/IE

    Installed Google Sign-in button per

    In Edge and IE 11, an exception is thrown at page load, and clicking the Sign-In button afterwards does nothing.

    Error in console: cb=gapi.loaded_0 (107,58)

    Line 107 from I marked the offending throw statement in asterisks.

    var tp,$o,ep,Yo;tp=function(a){_.D.setTimeout(function(){***throw a;***},0)};_.qk=function(a){a=Yo(a);!_.vd(_.D.setImmediate)||_.D.Window&&_.D.Window.prototype&&!"Edge")&&_.D.Window.prototype.setImmediate==_.D.setImmediate?($o||($o=ep()),$o(a)):_.D.setImmediate(a)};

    Wish I had the unminified version!

  • 5

    "Uncaught TypeError: Cannot read property 'sub' of null" when calling [gapi.auth.authorize(..)] for BigQuery

    From [email protected] on October 21, 2013 22:02:54

    What steps will reproduce the problem? If possible, provide a live demo of the issue. 1. load " " 2. In the handleClientLoad function call gapi.auth.authorize with the required params (clientid and scope(s))
    3. We're using scope " "

    What is the expected output?

    No error. Authorize is successful when signed in.

    What do you see instead?

    Error in console: "Uncaught TypeError: Cannot read property 'sub' of null" on line 282 of gapi library What version of the product are you using? On what operating system? /Ubuntu 13.04 Please provide any additional information below. This error has suddenly appeared today. We have not changed anything. Code snippet to highlight problem is below. We don't reach "handleAuthResult" anymore.

    function handleClientLoad() {
    alert('handleClientLoad'); //reached
    window.setTimeout(function() {checkAuth(true)}, 1);


    function checkAuth(immediate) { alert('checkAuth'); //reached gapi.auth.authorize({client_id: CLIENT_ID, scope: [BQ_SCOPE], immediate: true}, handleAuthResult); }

    function handleAuthResult(authResult) { alert('checkAuth'); //don't get here anymore }

    Original issue:

  • 6

    Google Sign-In now returning error popup_closed_by_user

    Our Electron desktop application has been using Google Sign-In for months now without any issues. But all of a sudden, starting today, Google Sign-In from our Electron desktop app started returning the "popup_closed_by_user" error. The login pop-up properly renders and you can successfully login to your Google account, but when the pop-up closes, instead of it properly logging in the user, it returns the popup_closed_by_user error.

    Google Sign-In continues to work fine for our website from web browsers like Chrome, Safari, and Firefox, but no longer works from our Electron desktop app.

    It appears there has been some kind of regression in the Google Sign-In service?

    Our google auth code for reference:

    var googleAuth
    gapi.load('auth2', function() {
        googleAuth = gapi.auth2.init({
            client_id: 'XXX',
            scope: 'email profile',
            fetch_basic_profile: false
    function beginGoogleAuth() {
            prompt: 'select_account',
            redirect_uri: 'postmessage'
        }).then(function(response) {
            document.getElementById('login-google-auth-code').value = response.code
  • 7

    gapi.auth2.getAuthInstance().signIn() promise then() not called + listeners not called

    Hi I was trying to use this library for authentication and I'm able to display the login pop-up but after logging in it doesn't call any of the Promise .thens or the isSignedIn and currentUser listeners.

            client_id: googleClientId,
          }).then(() => {
            console.log('signed in', window.gapi.auth2.getAuthInstance().isSignedIn.get());
            window.gapi.auth2.getAuthInstance().isSignedIn.listen((signedIn) => {
            window.gapi.auth2.getAuthInstance().currentUser.listen((user) => {

    (some time later)

    window.gapi.auth2.getAuthInstance().signIn().then((...args) => console.log(args), (...args) => console.log(args));

    I'm just going to go back to writing my own with the REST interface, but was curious as to what's going on.

  • 8

    TypeError: Cannot read property 'src' of null

    We're seeing lot's of these error occurring for some of our users, to the tune of about 2000 errors per hour when it happens. We can't determine the cause of the error as we've never repro'd it internally--we only know of it's existence because we log JS Errors in order to monitor the stability of our web app.

    Wondering if we can get any insight on what might cause this.

    Here's the stack trace we get from this error:

    TypeError: Cannot read property 'src' of null at Object.$d ( at c ( at e.invokeTask ( at n.runTask ( at invoke (

    The somewhat beautified minified code where this is coming from looks like:

    $d:function(a){ var c=t(a); a=c ? c:(c=l(a)) ? C.origin : ".."==a ? Rw.parent : window.document.getElementById(a).src; <== this is the 'src' in the error return h(a); }

    function c(a){ var c=(0,.of)(; if(c && c.f){ (0,.Fc)("gadgets.rpc.receive(""): "; var g=_.T.$d(c.f); <== this is where the above function is called ==================== H && ("undefined"!==typeof a.origin) ? a.origin!==g : a.domain!==/^.+://([^:]+).*/.exec(g)[1]) ?"Invalid rpc message origin. "+g+" vs "+(a.origin||"")):f(c,a.origin) } }

  • 9

    gapi.client.load started failing on 7/26/2013 - DOM Exception 12 (An invalid or illegal string was specified) error when calling .load

    From [email protected] on July 27, 2013 20:17:35

    What steps will reproduce the problem? If possible, provide a live demo of the issue. 1. I have written a PhoneGap application using the approach described at this web site: This PhoneGap application essentially allows the use of Google APIs (using the Google API Javascript client) to act as an 'offline web server' client to allow the OAuth API to work from an http://localhost source (the PhoneGap app).

    1. To accomplish this, the app loads the JavaScript client library in index.html with this call:

      3. This library successfully loads and onLoadCallback is called. (I have a console.log message show that it's called.

      Inside onLoadCallback, gapi.client has been initialized. So, I call:

      gapi.client.load('plus', 'v1', function() { console.log('plus loaded!'); });

    2. The callback is never called. If I hook this up to see what's going on in the Javascript, I see the following error in the console: a DOM Exception 12 ("An invalid or illegal string was specified.") in what appears to be in response to something in the gapi.client call (the reference in the Chrome Javascript console is: 5. If I comment out the gapi.client.load, this error does not appear. So, since the error reference is from, I'm quite sure that this error occurs during the call to gapi.client.load What is the expected output? What do you see instead? Of special importance: This EXACT CODE (not a single change) worked fine on the evening of 7/25/2013. This behavior started when I got back to work on the morning of 7/26/2013. So, I believe something changed recently that caused this new, error behavior. The code at the website mentioned above has been working since Sept. 2012 and my code has been working since early June (when I started using this model based on the web site). I have contacted the person who posted the web site above and he indicates that his app has stopped working with the same behavior on the same date. What version of the product are you using? On what operating system? I am dynamically load the client.js. So, this worked on and prior to 7/25/2013 and seems to have broken approx. 7/26/2013.

    I am using PhoneGap 2.8 and the app is failing as shown above on an iPad and in the Xcode iPad/iPhone simulator running iOS 6.1.3 (latest version)

    Original issue:

  • 10

    `popup_closed_by_user` thrown when calling `signIn` in Chrome

    From all of the browsers I've tested, this only seems to occur on Chrome, both incognito and in an authenticated browser. First, I check if the gapi object is properly authenticated. If not, I call the signIn method to authenticate. If the browser is not authenticated, the popup works as intended and I am able to sign in and then the signIn promise resolves. However, if the browser is already linked to a Google account, the popup opens and immediately closes (I assume this is because it is trying to use the authenticated account). This causes the popup_closed_by_user exception to be thrown and the gapi object is never authenticated. Below is the code.

    const auth = gapi.auth2.getAuthInstance();
    if (!auth.isSignedIn.get()) {
       auth.signIn().then(() => // Do the thing);
    } else {
       // Do the thing
  • 11

    URGENT - Google Drive SDK JavaScript 404 Error on any method

    From [email protected] on April 08, 2014 00:39:05

    We are getting since yesterday an error each time we try to execute any Drive Method from Javascript Library, such as:{'fileId': RootFolderID});{'folderId' : FolderGUID, 'q': 'trashed = ' + trashed}); Or any other.

    When we execute this code code:

    var RootFolderID = "0Bz9GhmOJPXaDMmlnc1UtNmFKb28";
    var GetFileInfo ={'fileId': RootFolderID});
        log("RootFolderID", RootFolderID);
        log("GetFileInfoResp", GetFileInfoResp);

    We get the following error

    RootFolderID - 0Bz9GhmOJPXaDMmlnc1UtNmFKb28

    GetFileInfoResp- Object {code: 404, message: "Not Found", data: Array[1], error: Object} code: 404 data: Array[1] error: Object message: "Not Found" proto: Object

    Two days ago the same code was working fine.

    Anyone has the same problem? do you have any clue?

    Original issue:

  • 12

    Cookie g_state is invalid

    Summary I'm trying to integrate the Google One Tap button into my Python web application and found out that the cookie g_state, which client script [1] uses to manage state, has not valid value format for cookies: g_state: {"i_l":0}. Because of that, the parser (std) on the Python side fails to parse such cookie value.

    Python 3.9.15 (main, Oct 25 2022, 06:48:03) 
    In [1]: from http.cookies import SimpleCookie
    In [2]: SimpleCookie('a=b; g_state={"i_l":0}; c=d;')
    Out[2]: <SimpleCookie: a='b'> 

    I'm also not the first person who encountered with the same problem:

    1. question on StackOverflow
    2. bug reporton the Python issue tracker
    3. discussion on Chromium-discuss.

    Could you change value of the cookie to something else, which will be more compatible with Cookie specs?

  • 13

    Google One Tap Javascript API/HTML API does not return nonce in JWT in Safari

    Hi Team,

    Summary When Google One Tap is implemented using Javascript API/HTML API including nonce, the returned JWT is missing nonce for Safari browser. Chrome and Fireforx returns the nonce as expected.

    Please refer the code used.

     const initializeGSI = () => {{
          client_id: '',
          cancel_on_tap_outside: false,
          nonce: '7342364',
          callback: onOneTapSignedIn

    Using "itp_support" did not make any change on this.

    This behaviour remains same for both Javascript API and HTML API.

    When "Prevent cross-site tracking" is disabled at Safari, the nonce returns and works as expected. Since Safari has this default setting, we have to request customers to disable this option to enable Google One Tap. Any workaround available ?

    Browser(s)/Version(s) Safari Version 16.1 (18614.

    Expected Behavior Google One Tap should return nonce in JWT when it is included in initialiaze call.

    Actual Behavior Returned JWT is missing nonce even it is included at initialize

    Steps to Reproduce Please include steps and code samples to aid in issue reproduction(html/javascript).

    Integrate Google One Tap using Javascript API/HTML API using a nonce. Sign in via Google One Tap Check retuned JWT

     const initializeGSI = () => {{
          client_id: '',
          cancel_on_tap_outside: false,
          nonce: 'y78745XXXXXXXX',
          callback: onOneTapSignedIn
  • 14

    Calling gapi.load('picker') again after a timeout doesn't reload the picker

    Summary I have a method that uses gapi.load to load the Google Drive file picker. I noticed that if the first call to gapi.load timesout, the subsequent calls will not load the picker correctly (i.e the gapi.picker object is missing from the global variable)

        loadGoogleDriveFilePicker() {
          return new Promise((resolve, reject) => {
            gapi.load('picker', {
              callback: function() {
              onerror: function() {
                reject(new Error(...))
              timeout: API_LOAD_TIMEOUT // equal to 4 seconds,
              ontimeout: function() {
                reject(new Error(...))

    Browser(s)/Version(s) Chrome 107.0.5304.121

    Expected Behavior We are able to reload the picker if a timeout occurs the first time.

    Actual Behavior The call to gapi.load('picker', ...) resolves but the gapi.picker object is missing from the global variable

    Steps to Reproduce

    1. Call gapi.load('picker', ...) with a small timeout (10ms)
    2. When the call to load the script times out, call the gapi.load('picker', ...) again with a longer timeout (10seconds)
    3. Note that the callback method is called (instead of the ontimeout callback) but gapi.picker is not available.
  • 15

    Official sample for Photos api albums.list throws exception.

    I am following the try me sample provided in Method: albums.list

    <script src=""></script>
       * Sample JavaScript code for photoslibrary.albums.list
       * See instructions for running APIs Explorer code samples locally:
      function authenticate() {
        return gapi.auth2.getAuthInstance()
            .signIn({scope: ""})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Error signing in", err); });
      function loadClient() {
        return gapi.client.load("$discovery/rest?version=v1")
            .then(function() { console.log("GAPI client loaded for API"); },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      // Make sure the client is loaded and sign-in is complete before calling this method.
      function execute() {
        return gapi.client.photoslibrary.albums.list({})
            .then(function(response) {
                    // Handle the results here (response.result has the parsed body).
                    console.log("Response", response);
                  function(err) { console.error("Execute error", err); });
      gapi.load("client:auth2", function() {
        gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
    <button onclick="authenticate().then(loadClient)">authorize and load</button>
    <button onclick="execute()">execute</button>

    All i have changed is adding my client id and api key

    "You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated. New clients must use the new libraries instead; existing clients must also migrate before these libraries are deprecated. See the Migration Guide for more information." error : "idpiframe_initialization_failed"

    I suspect this is related to the change to web identity but i have not been able to find a working example for Authorization with a google api.

  • 16

    Readme should indicate deprecation

    Important gapi.auth2 notice: gapi.auth2 has been deprecated and replaced with Google Identity Services. Please see for more information. If you have questions related to authentication/authorization please look at the associated documentation or post questions on Stack Overflow with the google-oauth tag.

    Summary I began using the gapi library and later found out it was deprecated. This could have been avoided if a deprecation notice were in the readme for this repository.

    Browser(s)/Version(s) all

    Expected Behavior I should be pointed to the new library for OAuth

    Actual Behavior I spent a day implementing OAuth with gapi and then stumbled on the deprecation notice in Google Identity docs.

    Steps to Reproduce Look at the readme without looking at the updated Google Identity docs.

  • 17

    error_callback for authentication flow

    The previous version of the Google Sign In Library allowed clients to specify an error_callback in case the user dismissed the popup etc. In the new identity services library, I see this is defined for the authorization flow but not with authentication. We rely on these callbacks for our internal logging. Is there a replacement I'm missing in the documentation or is this by design? Thanks!