AI-generated Key Takeaways
- 
          Support for the Google Sign-In library is deprecated and its use of FedCM APIs will become a requirement, so conduct an impact assessment to ensure user sign-in continues to function correctly. 
- 
          To implement Google Sign-In, load the Google APIs platform library and then the auth2library.
- 
          The gapi.auth2.init()method initializes theGoogleAuthobject, configuring it with your client ID and options, and potentially restoring a previous user session.
- 
          The GoogleAuthobject provides methods for signing users in and out, checking sign-in status, getting user profile information, requesting additional scopes, and revoking granted scopes.
- 
          You can use gapi.signin2.render()to display a customizable Google Sign-In button on your webpage.
This reference describes the JavaScript client methods and attributes you will use to implement Google Sign-In in your web applications.
If you encounter any issue using the library, report it to our GitHub repository. .
Auth Setup
Load the Google APIs platform library to create the gapi object:
<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
After the platform library loads, load the auth2 library:
function init() {
  gapi.load('auth2', function() {
    /* Ready. Make a call to gapi.auth2.init or some other API */
  });
}
gapi.auth2.init(params)
Initializes the GoogleAuth object. You must call this method before calling
gapi.auth2.GoogleAuth's methods.
When you initialize the GoogleAuth object, you configure the object with your
OAuth 2.0 client ID and any additional options you want to specify. Then, if the
user has already signed in, the GoogleAuth object restores the user's sign-in
state from the previous session.
| Arguments | |
|---|---|
| params | An object containing key-value pairs of client configuration data. See gapi.auth2.ClientConfigfor the different
      properties configurable. For example:{
  client_id: 'CLIENT_ID.apps.googleusercontent.com'
} | 
| Returns | |
|---|---|
| gapi.auth2.GoogleAuth | The gapi.auth2.GoogleAuthobject. Use the
    then() method to get a Promise
    that is resolved when thegapi.auth2.GoogleAuthobject finishes
    initializing. | 
GoogleAuth.then(onInit, onError)
Calls the onInit function when the GoogleAuth object is fully
initialized. If an error is raised while initializing (this can happen in old
unsupported browsers), the onError function will be called instead.
| Arguments | |
|---|---|
| onInit | The function called with the GoogleAuthobject when it is fully
      initialized. | 
| onError | The function called with an object containing an errorproperty,
      ifGoogleAuthfailed to initialize. | 
| Returns | |
|---|---|
| Promise | A Promisethat is fulfilled when the onInit
    function has completed, or rejected if an initialization error was raised. It resolves with the
    returned value from the onInit function, if any. | 
Error Codes
- idpiframe_initialization_failed
- 
    Failed to initialize a required iframe from Google, for example, due to an unsupported
    environment. A detailsproperty will give more information on the error raised.
gapi.auth2.ClientConfig
Interface that represents the different configuration parameters for the
gapi.auth2.init method.
| Parameters | ||
|---|---|---|
| client_id | string | Required. The app's client ID, found and created in the Google API Console. | 
| cookie_policy | string | The domains for which to create sign-in cookies. Either a URI, single_host_origin, ornone. Defaults tosingle_host_originif unspecified. | 
| scope | string | The scopes to request, as a space-delimited string. Optional if fetch_basic_profileis not set to false. | 
| fetch_basic_profile | boolean | Fetch users' basic profile information when they sign in. Adds 'profile', 'email' and 'openid' to the requested scopes. True if unspecified. | 
| hosted_domain | string | The G Suite domain to which users must belong to sign in. This
    is susceptible to modification by clients, so be sure to verify the
    hosted domain property of the returned user. Use
    GoogleUser.getHostedDomain() on
    the client, and the hdclaim in the ID Token on the
    server to verify the domain is what you expected. | 
| use_fedcm | boolean | Optional, defaults to True. Enable or disable the use of
    browser FedCM APIs during sign-in. | 
| ux_mode | string | The UX mode to use for the sign-in flow. By default, it will open the consent flow
      in a popup. Valid values are popupandredirect. | 
| redirect_uri | string | If using ux_mode='redirect', this parameter lets you override the
      defaultredirect_urithat will be used at the end of the consent flow. The
      defaultredirect_uriis the current URL stripped of query parameters and hash
      fragment. | 
| enable_granular_consent | boolean | Optional. Whether to enable
    granular
    permissions. If set to false, the more granular Google
    Account permissions will be disabled for OAuth client IDs created before
    2019.  No effect for OAuth Client IDs created during or after 2019, since
    more granular permissions is always enabled for them. | 
| plugin_name | string | Optional. Applies only to Client IDs created before March 3rd, 2025
      otherwise no effect.
      Enables existing web apps to continue using the Google Platform Library.
      By default, newly created Client IDs are blocked from using the Platform
      Library and instead must use the newer Google Identity Services library. You may choose any value, a descriptive name such as product or plugin name is recommended for identification. For example: plugin_name: 'YOUR_STRING_HERE' | 
Authentication
GoogleAuth is a singleton class that provides methods to allow the user to
sign in with a Google Account, get the user's current sign-in status, get
specific data from the user's Google profile, request additional scopes, and
sign out from the current account.
gapi.auth2.getAuthInstance()
Returns the GoogleAuth object. You must initialize the GoogleAuth object
with gapi.auth2.init() before calling this method.
| Returns | |
|---|---|
| gapi.auth2.GoogleAuth | The gapi.auth2.GoogleAuthobject. Use this object to callgapi.auth2.GoogleAuth's methods. | 
GoogleAuth.isSignedIn.get()
Returns whether the current user is signed in.
| Returns | |
|---|---|
| Boolean | trueif the user is signed in, orfalseif the
      user is signed out or theGoogleAuthobject isn't
      initialized. | 
GoogleAuth.isSignedIn.listen(listener)
Listen for changes in the current user's sign-in state.
| Arguments | |
|---|---|
| listener | A function that takes a boolean value. listen()passestrueto this function when the user signs in, andfalsewhen the user signs out. | 
GoogleAuth.signIn()
Signs in the user with the options specified to gapi.auth2.init().
| Returns | |
|---|---|
| Promise | A Promisethat is fulfilled with theGoogleUserinstance when the
    user successfully authenticates and grants the requested scopes, or rejected with an object
    containing anerrorproperty if an error happened. See the
    next section for error codes. | 
Error codes
See GoogleAuth.signIn(options).
GoogleAuth.signIn(options)
Signs in the user using the specified options.
| Arguments | |
|---|---|
| options | Either: 
 | 
| Returns | |
|---|---|
| Promise | A Promisethat is fulfilled with theGoogleUserinstance when the
    user successfully authenticates and grants the requested scopes, or rejected with an object
    containing anerrorproperty if an error happened (see below for error codes). | 
Error codes
- popup_closed_by_user
- The user closed the popup before finishing the sign in flow.
- access_denied
- The user denied the permission to the scopes required.
- immediate_failed
- 
    No user could be automatically selected without prompting the consent flow. Error raised when
    using signInwithprompt: 'none'option. This option shouldn't be required to use, asgapi.auth2.initwill automatically sign in the user if previously signed in during a previous session.
gapi.auth2.SignInOptions
Interface that represents the different configuration parameters for the
GoogleAuth.signIn(options) method.
| Parameters | ||
|---|---|---|
| prompt | string | Forces a specific mode for the consent flow. Optional. The possible values are: 
 | 
| scope | string | The scopes to request, as a space-delimited string, on top of the scopes defined in the gapi.auth2.initparams. Optional iffetch_basic_profileis not set
      to false. | 
| ux_mode | string | The UX mode to use for the sign-in flow. By default, it will open the consent flow
      in a popup. Valid values are popupandredirect. | 
| redirect_uri | string | If using ux_mode='redirect', this parameter lets you override
      the defaultredirect_urithat will be used at the end of the consent
      flow. The defaultredirect_uriis the current URL stripped of query
      parameters and hash fragment. | 
GoogleAuth.signOut()
Signs out the current account from the application.
| Returns | |
|---|---|
| Promise | A Promisethat is fulfilled when the user has been signed
    out. | 
GoogleAuth.disconnect()
Revokes all of the scopes that the user granted.
GoogleAuth.grantOfflineAccess(options)
Get permission from the user to access the specified scopes offline.
| Arguments | |
|---|---|
| options | A gapi.auth2.OfflineAccessOptionsobject containing key-value pairs of parameters. For example:{
  scope: 'profile email'
} | 
| Returns | |
|---|---|
| Promise | A Promisethat is fulfilled when the user grants the
    requested scopes, passing an object containing the authorization code to
    thePromise's fulfillment handler.
    For example:auth2.grantOfflineAccess().then(function(resp) { var auth_code = resp.code; }); | 
Error codes
- popup_closed_by_user
- The user closed the popup before finishing the consent flow.
- access_denied
- The user denied the permission to the scopes required.
- immediate_failed
- 
    No user could be automatically selected without prompting the consent flow. Error raised when
    using signInwithprompt: 'none'option. This option should not be required to use, asgapi.auth2.initwill automatically sign in the user if previously signed in during a previous session.
gapi.auth2.OfflineAccessOptions
Interface that represents the different configuration parameters for the
GoogleAuth.grantOfflineAccess(options) method.
| Parameters | ||
|---|---|---|
| prompt | string | Forces a specific mode for the consent flow. Optional. The possible values are: 
 | 
| scope | string | The scopes to request, as a space-delimited string, on top of the scopes defined in the gapi.auth2.initparams. Optional iffetch_basic_profileis not set
      to false. | 
GoogleAuth.attachClickHandler(container, options, onsuccess, onfailure)
Attaches the sign-in flow to the specified container's click handler.
| Arguments | |
|---|---|
| container | The ID of, or a reference to, the divelement to which to
    attach the click handler. | 
| options | An object containing key-value pairs of parameters. See GoogleAuth.signIn(). | 
| onsuccess | The function to call after sign-in completes. | 
| onfailure | The function to call if sign-in fails. | 
Users
A GoogleUser object represents one user account. GoogleUser objects are
typically obtained by calling
GoogleAuth.currentUser.get().
GoogleAuth.currentUser.get()
Returns a GoogleUser object
that represents the current user. Note that in a newly-initialized
GoogleAuth instance, the current user has not been set. Use the
currentUser.listen() method or the GoogleAuth.then()
to get an initialized GoogleAuth instance.
| Returns | |
|---|---|
| GoogleUser | The current user | 
GoogleAuth.currentUser.listen(listener)
Listen for changes in currentUser.
| Arguments | |
|---|---|
| listener | A function that takes a GoogleUserparameter.listenpasses this function aGoogleUserinstance on every change that modifiescurrentUser. | 
GoogleUser.getId()
Get the user's unique ID string.
| Returns | |
|---|---|
| String | The user's unique ID | 
GoogleUser.isSignedIn()
Returns true if the user is signed in.
| Returns | |
|---|---|
| Boolean | True if the user is signed in | 
GoogleUser.getHostedDomain()
Get the user's G Suite domain if the user signed in with a G Suite account.
| Returns | |
|---|---|
| String | The user's G Suite domain | 
GoogleUser.getGrantedScopes()
Get the scopes that the user granted as a space-delimited string.
| Returns | |
|---|---|
| String | The scopes granted by the user | 
GoogleUser.getBasicProfile()
Get the user's basic profile information.
| Returns | |
|---|---|
| gapi.auth2.BasicProfile | You can retrieve the properties of gapi.auth2.BasicProfilewith the following methods:
 | 
GoogleUser.getAuthResponse(includeAuthorizationData)
Get the response object from the user's auth session.
| Arguments | |
|---|---|
| includeAuthorizationData | Optional: A boolean that specifies whether to always return an access token and
      scopes. By default, the access token and requested scopes are not returned when fetch_basic_profileis true (the default value) and no additional scopes are
      requested. | 
| Returns | |
|---|---|
| gapi.auth2.AuthResponse | A gapi.auth2.AuthResponseobject. | 
GoogleUser.reloadAuthResponse()
Forces a refresh of the access token, and then returns a Promise for the new AuthResponse.
| Returns | |
|---|---|
| Promise | A Promisethat is fulfilled with the reloadedgapi.auth2.AuthResponsewhen reloading the
      OAuth token is done. | 
gapi.auth2.AuthResponse
  The response returned when calling
  GoogleUser.getAuthResponse(includeAuthorizationData)
  or
  GoogleUser.reloadAuthResponse()
  methods.
| Properties | ||
|---|---|---|
| access_token | string | The Access Token granted. | 
| id_token | string | The ID Token granted. | 
| scope | string | The scopes granted in the Access Token. | 
| expires_in | number | The number of seconds until the Access Token expires. | 
| first_issued_at | number | The timestamp at which the user first granted the scopes requested. | 
| expires_at | number | The timestamp at which the Access Token will expire. | 
GoogleUser.hasGrantedScopes(scopes)
Returns true if the user granted the specified scopes.
| Arguments | |
|---|---|
| scopes | A space-delimited string of scopes. | 
| Returns | |
|---|---|
| Boolean | True if the scopes were granted | 
GoogleUser.grant(options)
Request additional scopes to the user.
See GoogleAuth.signIn() for the
list of parameters and the error code.
GoogleUser.grantOfflineAccess(options)
Get permission from the user to access the specified scopes offline.
| Arguments | |
|---|---|
| options | A gapi.auth2.OfflineAccessOptionsobject containing key-value pairs of parameters. For example:{
  scope: 'profile email'
} | 
GoogleUser.disconnect()
Revokes all of the scopes that the user granted for the application.
UI elements
gapi.signin2.render(id, options)
Renders a sign-in button in the element with the given ID, using the settings specified by the options object.
| Arguments | |||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| id | The ID of the element in which to render the sign-in button. | ||||||||||||||||
| options | An object containing the settings to use to render the button. For example: {
  scope: 'email',
  width: 200,
  height: 50,
  longtitle: true,
  theme: 'dark',
  onsuccess: handleSuccess,
  onfailure: handleFailure
}
 | ||||||||||||||||
Advanced
gapi.auth2.authorize(params, callback)
Performs a one time OAuth 2.0 authorization. Depending on the parameters used, this will open a popup to the Google sign-in flow or try to load the requested response silently, without user interaction.
Some use cases where this method is useful include:
- Your application only needs to requests a Google API endpoint once, for example to load the user's favorite YouTube videos the first time they sign in.
- Your application has its own session management infrastructure, and it only requires the ID Token once to identify the user in your backend.
- Several Client IDs are used within the same page.
| Arguments | |
|---|---|
| params | An object containing key-value pairs of configuration data. See gapi.auth2.AuthorizeConfigfor the
      different properties configurable. For example:{ client_id: 'CLIENT_ID.apps.googleusercontent.com', scope: 'email profile openid', response_type: 'id_token permission' } | 
| callback | A function called with a gapi.auth2.AuthorizeResponseobject
      after the request has been completed (either successfully or with a failure). | 
Example
gapi.auth2.authorize({
  client_id: 'CLIENT_ID.apps.googleusercontent.com',
  scope: 'email profile openid',
  response_type: 'id_token permission'
}, function(response) {
  if (response.error) {
    // An error happened!
    return;
  }
  // The user authorized the application for the scopes requested.
  var accessToken = response.access_token;
  var idToken = response.id_token;
  // You can also now use gapi.client to perform authenticated requests.
});
Error codes
- idpiframe_initialization_failed
- 
    Failed to initialize a required iframe from Google, for example, due to an unsupported
    environment. A detailsproperty will give more information on the error raised.
- popup_closed_by_user
- The user closed the popup before finishing the sign in flow.
- access_denied
- The user denied the permission to the scopes required.
- immediate_failed
- 
    No user could be automatically selected without prompting the consent flow. Error raised when
    using signInwithprompt: 'none'option.
gapi.auth2.AuthorizeConfig
Interface that represents the different configuration parameters for the
gapi.auth2.authorize method.
| Properties | ||
|---|---|---|
| client_id | string | Required. The app's client ID, found and created in the Google API Console. | 
| scope | string | Required. The scopes to request, as a space-delimited string. | 
| response_type | string | A list of space-delimited response type. Defaults to 'permission'. The possible
      values are:
 | 
| prompt | string | Forces a specific mode for the consent flow. The possible values are: 
 | 
| cookie_policy | string | The domains for which to create sign-in cookies. Either a URI, single_host_origin, ornone. Defaults tosingle_host_originif unspecified. | 
| hosted_domain | string | The G Suite domain to which users must belong to sign in. This is susceptible to modification by clients, so be sure to verify the hosted domain property of the returned user. | 
| login_hint | string | The email, or User ID, of a user to pre-select in the sign-in flow. This is susceptible to
      modification by the user, unless prompt: "none"is used. | 
| include_granted_scopes | boolean | Whether to request an Access Token that includes all the scopes previously granted by the user
      to the app, or only the scopes requested in the current call. Defaults to true. | 
| enable_granular_consent | boolean | Optional. Whether to enable
      granular
      permissions. If set to false, the more granular Google
      Account permissions will be disabled for OAuth client IDs created before
      2019. No effect for OAuth Client IDs created during or after 2019, since
      more granular permissions is always enabled for them. | 
| plugin_name | string | Optional. Applies only to Client IDs created before March 3rd, 2025
      otherwise no effect.
      Enables existing web apps to continue using the Google Platform Library.
      By default, newly created Client IDs are blocked from using the Platform
      Library and instead must use the newer Google Identity Services library. You may choose any value, a descriptive name such as product or plugin name is recommended for identification. For example: plugin_name: 'YOUR_STRING_HERE' | 
gapi.auth2.AuthorizeResponse
The response returned to the callback of the
gapi.auth2.authorize method.
| Properties | ||
|---|---|---|
| access_token | string | The Access Token granted. Only present if permissionortokenwas
      specified in theresponse_type. | 
| id_token | string | The ID Token granted. Only present if id_tokenwas specified in theresponse_type. | 
| code | string | The Authorization Code granted. Only present if codewas specified in theresponse_type. | 
| scope | string | The scopes granted in the Access Token. Only present if permissionortokenwas specified in theresponse_type. | 
| expires_in | number | The number of seconds until the Access Token expires. Only present if permissionortokenwas specified in theresponse_type. | 
| first_issued_at | number | The timestamp at which the user first granted the scopes requested. Only present if permissionortokenwas specified in theresponse_type. | 
| expires_at | number | The timestamp at which the Access Token will expire. Only present if permissionortokenwas specified in theresponse_type. | 
| error | string | When the request failed, this contains the error code. | 
| error_subtype | string | When the request failed, this can contain additional information to the error code also returned. |