Warning: This data is provided under the Google User Data Policy. Please review and comply with the policy. Failure to do so might result in project or account suspension.

Sign In With Google JavaScript API reference

This reference page describes the Sign-In JavaScript API. You can use this API to display the One Tap prompt or Sign In With Google button on your web pages.

Method: google.accounts.id.initialize

The google.accounts.id.initialize method initializes the Sign In With Google client based on the configuration object. See the following code example of the method:

google.accounts.id.initialize(IdConfiguration)

The following code example implements the google.accounts.id.initialize method with an onload function:

<script>
  window.onload = function () {
    google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: handleCredentialResponse
    });
    google.accounts.id.prompt();
  };
</script>

Data type: IdConfiguration

The following table lists the fields and descriptions of the IdConfiguration data type:

Field
client_id Your application's client ID
auto_select Enables automatic selection.
callback The JavaScript function that handles ID tokens. Google One Tap and the Sign In With Google button popup UX mode use this attribute.
login_uri The URL of your login endpoint. The Sign In With Google button redirect UX mode uses this attribute.
native_callback The JavaScript function that handles password credentials.
cancel_on_tap_outside Cancels the prompt if the user clicks outside the prompt.
prompt_parent_id The DOM ID of the One Tap prompt container element
nonce A random string for ID tokens
context The title and words in the One Tap prompt
state_cookie_domain If you need to call One Tap in the parent domain and its subdomains, pass the parent domain to this field so that a single shared cookie is used.
ux_mode The Sign In With Google button UX flow
allowed_parent_origin The origins that are allowed to embed the intermediate iframe. One Tap will run in the intermediate iframe mode if this field presents.
intermediate_iframe_close_callback Overrides the default intermediate iframe behavior when users manually close One Tap.

client_id

This field is your application's client ID, which is found and created in the Google Developers Console. See the following table for further information:

Type Required Example
string Yes client_id: "CLIENT_ID.apps.googleusercontent.com"

auto_select

This field determines if an ID token is automatically returned without any user interaction when there's only one Google session that has approved your app before. The default value is false. See the following table for further information:

Type Required Example
boolean Optional auto_select: true

callback

This field is the JavaScript function that handles the ID token returned from the One Tap prompt or the pop-up window. This attribute is required if Google One Tap or the Sign In With Google button popup UX mode is used. See the following table for further information:

Type Required Example
function Required for One Tap and the popup UX mode callback: handleResponse

login_uri

This attribute is the URI of your login endpoint. May be omitted if the current page is your login page, in which case the credential is posted to this page by default.

The ID token credential response is posted to your login endpoint when a user clicks on the Sign In With Google button and redirect UX mode is used.

See the following table for further information:

Type Optional Example
URL Defaults to the URI of the current page, or the value you specify.
Only used when ux_mode: "redirect" is set.
data-login_uri="https://www.example.com/login"

Your login endpoint must handle POST requests containing a credential key with an ID token value in the body.

The following is an example request to your login endpoint:

POST /login HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded

credential=ID_TOKEN

native_callback

This field is the name of the JavaScript function that handles the password credential returned from the browser's native credential manager. See the following table for further information:

Type Required Example
function Optional native_callback: handleResponse

cancel_on_tap_outside

This field sets whether or not to cancel the One Tap request if a user clicks outside the prompt. The default value is true. You can disable it if you set the value to false. See the following table for further information:

Type Required Example
boolean Optional cancel_on_tap_outside: false

prompt_parent_id

This attribute sets the DOM ID of the container element. If it's not set, the One Tap prompt is displayed in the top-right corner of the window. See the following table for further information:

Type Required Example
string Optional prompt_parent_id: 'parent_id'

nonce

This field is a random string used by the ID token to prevent replay attacks. See the following table for further information:

Type Required Example
string Optional nonce: "biaqbm70g23"

context

This field changes the text of the title and messages in the One Tap prompt. See the following table for further information:

Type Required Example
string Optional context: "use"

The following table lists the available contexts and their descriptions:

Context
signin "Sign in with Google"
signup "Sign up with Google"
use "Use with Google"

If you need to display One Tap in the parent domain and its subdomains, pass the parent domain to this field so that a single shared-state cookie is used. See the following table for further information:

Type Required Example
string Optional state_cookie_domain: "example.com"

ux_mode

Use this field to set the UX flow used by the Sign In With Google button. The default value is popup. This attribute has no impact on the OneTap UX. See the following table for further information:

Type Required Example
string Optional ux_mode: "redirect"

The following table lists the available UX modes and their descriptions.

UX Mode
popup Performs sign-in UX flow in a pop-up window.
redirect Performs sign-in UX flow by a full page redirection.

allowed_parent_origin

The origins that are allowed to embed the intermediate iframe. One Tap will run in the intermediate iframe mode if this field presents. See the following table for further information:

Type Required Example
string or string array Optional allowed_parent_origin: "https://example.com"

The following table lists the supported value types and their descriptions.

Value Types
string A single domain URI. "https://example.com"
string array An array of domain URIs. ["https://news.example.com", "https://local.example.com"]

Wildcard prefixes are also supported. For example, "https://*.example.com" will match example.com and its subdomains at all levels (e.g news.example.com, login.news.example.com). Things to keep in mind when using wildcards:

  • Pattern strings cannot be composed of only a wildcard and a top level domain. For example https://*.com and https://*.co.uk are invalid; As noted aboved, "https://*.example.com" will match example.com and its subdomains. You can also use an array to represent 2 different domains. For example, ["https://example1.com", "https://*.example2.com"] will match the domains example1.com, example2.com and subdomains of example2.com
  • Wildcard domains must begin with a secure https:// scheme. "*.example.com" will be considered invalid.

If the value of allowed_parent_origin field is invalid, the One Tap initialization of the intermediate iframe mode would fail and stop.

intermediate_iframe_close_callback

Overrides the default intermediate iframe behavior when users manually close One Tap by tapping on the 'X' button in the One Tap UI. The default behavior is to remove the intermediate iframe from the DOM immediately.

The intermediate_iframe_close_callback field takes effect only in intermediate iframe mode. And it has impact only to the intermediate iframe, instead of the One Tap iframe. The One Tap UI is removed before the callback is invoked.

Type Required Example
function Optional intermediate_iframe_close_callback: logBeforeClose

Method: google.accounts.id.prompt

The google.accounts.id.prompt method displays the One Tap prompt or the browser native credential manager after the initialize() method is invoked. See the following code example of the method:

 google.accounts.id.prompt(/**
 @type{(function(!PromptMomentNotification):void)=} */ momentListener)

Normally, the prompt() method is called on page load. Due to the session status and user settings on the Google side, the One Tap prompt UI might not be displayed. To get notified on the UI status for different moments, pass a function to receive UI status notifications.

Notifications are fired on the following moments:

  • Display moment: This occurs after the prompt() method is called. The notification contains a boolean value to indicate whether the UI is displayed or not.
  • Skipped moment: This occurs when the One Tap prompt is closed by an auto cancel, a manual cancel, or when Google fails to issue a credential, such as when the selected session has signed out of Google.

    In these cases, we recommend that you continue on to the next identity providers, if there are any.

  • Dismissed moment: This occurs when Google successfully retrieves a credential or a user wants to stop the credential retrieval flow. For example, when the user begins to input their username and password in your login dialog, you can call the google.accounts.id.cancel() method to close the One Tap prompt and trigger a dismissed moment.

The following code example implements the skipped moment:

<script>
  window.onload = function () {
    google.accounts.id.initialize(...);
    google.accounts.id.prompt((notification) => {
      if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
        // continue with another identity provider.
      }
    });
  };
</script>

Data type: PromptMomentNotification

The following table lists methods and descriptions of the PromptMomentNotification data type:

Method
isDisplayMoment() Is this notification for a display moment?
isDisplayed() Is this notification for a display moment, and the UI is displayed?
isNotDisplayed() Is this notification for a display moment, and the UI isn't displayed?
getNotDisplayedReason()

The detailed reason why the UI isn't displayed. The following are possible values:

  • browser_not_supported
  • invalid_client
  • missing_client_id
  • opt_out_or_no_session
  • secure_http_required
  • suppressed_by_user
  • unregistered_origin
  • unknown_reason
isSkippedMoment() Is this notification for a skipped moment?
getSkippedReason()

The detailed reason for the skipped moment. The following are possible values:

  • auto_cancel
  • user_cancel
  • tap_outside
  • issuing_failed
isDismissedMoment() Is this notification for a dismissed moment?
getDismissedReason()

The detailed reason for the dismissal. The following are possible values:

  • credential_returned
  • cancel_called
  • flow_restarted
getMomentType()

Return a string for the moment type. The following are possible values:

  • display
  • skipped
  • dismissed

Data type: CredentialResponse

When your callback function is invoked, a CredentialResponse object is passed as the parameter. The following table lists the fields that are contained in the credential response object:

Field
credential This field is the returned ID token.
select_by This field sets how the credential is selected.
client_id This field sets the OAuth client ID.

credential

This field is the ID token as a base64-encoded JSON Web Token (JWT) string.

When decoded, the JWT looks like the following example:

header
{
  "alg": "RS256",
  "kid": "f05415b13acb9590f70df862765c655f5a7a019e", // JWT signature
  "typ": "JWT"
}
payload
{
  "iss": "https://accounts.google.com", // The JWT's issuer
  "nbf":  161803398874,
  "aud": "314159265-pi.apps.googleusercontent.com", // Your server's client ID
  "sub": "3141592653589793238", // The unique ID of the user's Google Account
  "hd": "gmail.com", // If present, the host domain of the user's GSuite email address
  "email": "elisa.g.beckett@gmail.com", // The user's email address
  "email_verified": true, // true, if Google has verified the email address
  "azp": "314159265-pi.apps.googleusercontent.com",
  "name": "Elisa Beckett",
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/e2718281828459045235360uler",
  "given_name": "Eliza",
  "family_name": "Beckett",
  "iat": 1596474000, // Unix timestamp of the assertion's creation time
  "exp": 1596477600, // Unix timestamp of the assertion's expiration time
  "jti": "abc161803398874def"
}

The sub field contains a globally unique identifier for the Google account.

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verfied can also be true as Google initially verified the user when the Google account was created, however ownership of the third party email account may have since changed.

select_by

The following table lists the possible values for the select_by field. The type of button used along with the session and consent state are used to set the value,

  • The user pressed either the One Tap or Sign In With Google button or used the touchless Automatic sign-in process.

  • An existing session was found, or the user selected and signed-in to a Google Account to establish a new session.

  • Prior to sharing ID token credentials with your app the user either

    • pressed the Confirm button to grant their consent to share credentials, or
    • had previously granted consent and used Select an Account to choose a Google Account.

The value of this field is set to one of these types,

Value Description
auto Automatic sign-in of a user with an existing session who had previously granted consent to share credentials.
user A user with an existing session who had previously granted consent pressed the One Tap 'Continue as' button to share credentials.
user_1tap A user with an existing session pressed the One Tap 'Continue as' button to grant consent and share credentials. Applies only to Chrome v75 and higher.
user_2tap A user without an existing session pressed the One Tap 'Continue as' button to select an account and then pressed the Confirm button in a pop-up window to grant consent and share credentials. Applies to non-Chromium based browsers.
btn A user with an existing session who previously granted consent pressed the Sign In With Google button and selected a Google Account from 'Choose an Account' to share credentials.
btn_confirm A user with an existing session pressed the Sign In With Google button and pressed the Confirm button to grant consent and share credentials.
btn_add_session A user without an existing session who previously granted consent pressed the Sign In With Google button to select a Google Account and share credentials.
btn_confirm_add_session A user without an existing session first pressed the Sign In With Google button to select a Google Account and then pressed the Confirm button to consent and share credentials.

client_id

This field is the OAuth client ID.

Method: google.accounts.id.renderButton

The google.accounts.id.renderButton method renders a Sign In With Google button in your web pages.

See the following code example of the method:

google.accounts.id.renderButton(
    /** @type{!HTMLElement} */ parent,
    /** @type{!GsiButtonConfiguration} */ options,
    /** @type{function()=} */ clickHandler)

The following code example renders a Sign In With Google button on page load:

<script>
  window.onload = function () {
    google.accounts.id.initialize({
      client_id: '<var>YOUR_GOOGLE_CLIENT_ID</var>',
      callback: handleCredentialResponse
    });
    google.accounts.id.renderButton(buttonDiv, {
      theme: 'outline',
      size: 'large',
    });
  };
</script>

Data type: GsiButtonConfiguration

The following table lists the fields and descriptions of the GsiButtonConfiguration data type:

Attribute
type The button type: icon, or standard button.
theme The button theme. For example, white or blue.
size The button size. For example, samll or large.
text The button text. For example, "Sign in with Google" or "Sign up with Google".
shape The button shape. For example, rectangular or circular.
logo_alignment The Google logo alignment: left or center.
width The button width, in pixels.
locale If set, then the button language is rendered.

Attribute types

The following sections contain details about each attribute's type, and an example.

type

The button type. The default value is standard.

See the following table for further information:

Type Required Example
string Yes type: "icon"

The following table lists the available button types and their descriptions:

Type
standard A button with text or personalized information:
icon An icon button without text:

theme

The button theme. The default value is outline. See the following table for further information:

Type Required Example
string Optional theme: "filled_blue"

The following table lists the available themes and their descriptions:

Theme
outline A standard button theme:
filled_blue A blue-filled button theme:
filled_black A black-filled button theme:

size

The button size. The default value is large. See the following table for further information:

Type Required Example
string Optional size: "small"

The following table lists the available button sizes and their descriptions:

Size
large A large button:
A large standard button A large icon button A large, personalized button
medium A medium-sized button:
A medium standard button A medium icon button
small A small button:
A small button A small icon button

text

The button text. The default value is signin_with. There are no visual differences for the text of icon buttons that have different text attributes. The only exception is when the text is read for screen accessibility.

See the following table for further information:

Type Required Example
string Optional text: "signup_with"

The following table lists the available button texts and their descriptions:

Text
signin_with The button text is “Sign in with Google”:
signup_with The button text is “Sign up with Google”:
continue_with The button text is “Continue with Google”:
signup_with The button text is “Sign in”:

shape

The button shape. The default value is rectangular. See the following table for further information:

Type Required Example
string Optional shape: "rectangular"

The following table lists the available button shapes and their descriptions:

Shape
rectangular The rectangular-shaped button. If used for the icon button type, then it's the same as square.
pill The pill-shaped button. If used for the icon button type, then it's the same as circle.
circle The circle-shaped button. If used for the standard button type, then it's the same as pill.
square The square-shaped button. If used for the standard button type, then it's the same as rectangular.

logo_alignment

The alignment of the Google logo. The default value is left. This attribute only applies to the standard button type. See the following table for further information:

Type Required Example
string Optional logo_alignment: "center"

The following table lists the available alignments and their descriptions:

logo_alignment
left Left-aligns the Google logo.
center Center-aligns the Google logo.

width

The minimum button width, in pixels. The maximum width is 400 pixels.

See the following table for further information:

Type Required Example
string Optional width: 400

locale

The pre-set locale of the button text. If it's not set, the browser's default locale or the Google session user’s preference is used. Therefore, different users might see different versions of localized buttons, and possibly with different sizes.

See the following table for further information:

Type Required Example
string Optional locale: "zh_CN"

Data type: Credential

When your native_callback function is invoked, a Credential object is passed as the parameter. The following table lists the fields contained in the object:

Field
id Identifies the user.
password The password

Method: google.accounts.id.disableAutoSelect

When the user signs out of your website, you need to call the method google.accounts.id.disableAutoSelect to record the status in cookies. This prevents a UX dead loop. See the following code snippet of the method:

google.accounts.id.disableAutoSelect()

The following code example implements the google.accounts.id.disableAutoSelect method with an onSignout() function:

<script>
  function onSignout() {
    google.accounts.id.disableAutoSelect();
  }
</script>

Method: google.accounts.id.storeCredential

This method is a simple wrapper for the store() method of the browser's native credential manager API. Therefore, it can only be used to store a password credential. See the following code example of the method:

google.accounts.id.storeCredential(Credential, callback)

The following code example implements the google.accounts.id.storeCredential method with an onSignIn() function:

<script>
  function onSignIn() {
    let cred = {id: '...', password: '...'};
    google.accounts.id.storeCredential(cred);
  }
</script>

Method: google.accounts.id.cancel

You can cancel the One Tap flow if you remove the prompt from the relying party DOM. The cancel operation is ignored if a credential is already selected. See the following code example of the method:

google.accounts.id.cancel()

The following code example implements the google.accounts.id.cancel() method with an onNextButtonClicked() function:

<script>
  function onNextButtonClicked() {
    google.accounts.id.cancel();
    showPasswordPage();
  }
</script>

Library load callback: onGoogleLibraryLoad

You can register an onGoogleLibraryLoad callback. It's notified after the Sign In With Google JavaScript library is loaded:

window.onGoogleLibraryLoad = () => {
    ...
};

This callback is just a shortcut for the window.onload callback. There are no differences in behavior.

The following code example implements an onGoogleLibraryLoad callback:

<script>
  window.onGoogleLibraryLoad = () => {
   google.accounts.id.initialize({
     ...
   });
   google.accounts.id.prompt();
  };
</script>

Method: google.accounts.id.revoke

The google.accounts.id.revoke method revokes the OAuth grant used to share the ID token for the specified user. See the following code snippet of the method: google.accounts.id.revoke(hint, callback)

Parameter Type Description
hint string The email address or Credential id for the target Google user.
callback function Optional RevocationResponse handler.

The following code sample shows how use the revoke method with an Id.

  google.accounts.id.revoke('1618033988749895', done => {
    console.log(done.error);
  });

Data type: RevocationResponse

When your callback function is invoked, a RevocationResponse object is passed as the parameter. The following table lists the fields that are contained in the revocation response object:

Field
successful This field is the return value of the method call.
error This field optionally contains a detailed error response message.

successful

This field is a boolean value set to true if the revoke method call succeeded or false on failure.

error

This field is a string value and contains a detailed error message if the revoke method call failed, it is undefined on success.