### Install Project Dependencies Source: https://github.com/react-native-google-signin/docs/blob/main/README.md Run this command to install all necessary project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### Start Local Development Server Source: https://github.com/react-native-google-signin/docs/blob/main/README.md Starts a local development server for live previewing changes. Most updates reflect without a server restart. ```bash $ yarn start ``` -------------------------------- ### Install React Native Google Sign-In with Bun Source: https://github.com/react-native-google-signin/docs/blob/main/docs/install.mdx Install the latest version of the @react-native-google-signin/google-signin package using Bun. ```bash bun add @react-native-google-signin/google-signin@latest ``` -------------------------------- ### Example Config Doctor Output Source: https://github.com/react-native-google-signin/docs/blob/main/docs/config-doctor.mdx This is an example of the output you might see after running the configuration doctor, showing the application package name and found SHA-1 certificate fingerprints. ```text ✔ Application package name: com.some.app.android 🔍 Found the following SHA-1 certificate fingerprints: A1:B2:C3:D4:E5:F6:G7:H8:I9:J0:K1:L2:M3:N4:O5:P6:Q7:R8:S9:T0 Next steps: ... ``` -------------------------------- ### Example of calling the signIn() method Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx This snippet demonstrates how to call the `signIn` method for automatic user sign-in. It includes checks for Play Services availability, handling successful sign-ins, and managing cases where no saved credentials are found. It also shows basic error handling for Play Services issues and other potential errors. ```typescript import { GoogleOneTapSignIn, statusCodes, isErrorWithCode, isSuccessResponse, isNoSavedCredentialFoundResponse, } from '@react-native-google-signin/google-signin'; // Somewhere in your code const signIn = async () => { try { await GoogleOneTapSignIn.checkPlayServices(); const response = await GoogleOneTapSignIn.signIn(); if (isSuccessResponse(response)) { // read user's info console.log(response.data); } else if (isNoSavedCredentialFoundResponse(response)) { // Android and Apple only. // No saved credential found (user has not signed in yet, or they revoked access) // call `createAccount()` } } catch (error) { console.error(error); if (isErrorWithCode(error)) { switch (error.code) { case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: // Android: play services not available or outdated. // Get more details from `error.userInfo`. // Web: when calling an unimplemented api (requestAuthorization) // or when the Google Client Library is not loaded yet. break; default: // something else happened } } else { // an error that's not related to google sign in occurred } } }; ``` -------------------------------- ### Configure Jest Setup File Source: https://github.com/react-native-google-signin/docs/blob/main/docs/testing.md Add this to your Jest config's `setupFiles` array to mock the Google Sign-In native module. The mock defaults to successful calls with mock user data. ```json { "setupFiles": [ "./node_modules/@react-native-google-signin/google-signin/jest/build/jest/setup.js" ] } ``` -------------------------------- ### Install React Native Google Sign-In with npm Source: https://github.com/react-native-google-signin/docs/blob/main/docs/install.mdx Install the latest version of the @react-native-google-signin/google-signin package using npm. ```bash npm i @react-native-google-signin/google-signin@latest ``` -------------------------------- ### Install React Native Google Sign-In with Yarn Source: https://github.com/react-native-google-signin/docs/blob/main/docs/install.mdx Install the latest version of the @react-native-google-signin/google-signin package using Yarn. ```bash yarn add @react-native-google-signin/google-signin@latest ``` -------------------------------- ### Install React Native Google Sign-In with pnpm Source: https://github.com/react-native-google-signin/docs/blob/main/docs/install.mdx Install the latest version of the @react-native-google-signin/google-signin package using pnpm. ```bash pnpm add @react-native-google-signin/google-signin@latest ``` -------------------------------- ### Implementing sign-in flow Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Example of triggering the sign-in modal and handling success or error states using status codes. ```typescript // import statusCodes along with GoogleSignin import { GoogleSignin, statusCodes, } from '@react-native-google-signin/google-signin'; // Somewhere in your code const signIn = async () => { try { await GoogleSignin.hasPlayServices(); const response = await GoogleSignin.signIn(); if (isSuccessResponse(response)) { setState({ userInfo: response.data }); } else { // sign in was cancelled by user } } catch (error) { if (isErrorWithCode(error)) { switch (error.code) { case statusCodes.IN_PROGRESS: // operation (eg. sign in) already in progress break; case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: // Android only, play services not available or outdated break; default: // some other error happened } } else { // an error that's not related to google sign in occurred } } }; ``` -------------------------------- ### Get Raw Nonce and Nonce Digest with react-native-quick-crypto for Supabase Source: https://github.com/react-native-google-signin/docs/blob/main/docs/security.mdx Generates a raw nonce and its SHA-256 digest using `react-native-quick-crypto`. This is used when integrating with Supabase, where the raw nonce is passed to `signInWithIdToken` and the digest is used in Google Sign-In APIs. Ensure `react-native-quick-crypto` is installed. ```typescript import QuickCrypto from 'react-native-quick-crypto'; const getNonce = () => { // `rawNonce` goes to Supabase's signInWithIdToken(). // Supabase makes a hash of `rawNonce` and compares it with the `nonceDigest` // which is included in the ID token from RN-google-signin. const rawNonce = getUrlSafeNonce(); // `nonceDigest` (SHA-256 hash, hex-encoded) goes to the `nonce` parameter in RN-google-signin APIs const nonceDigest = QuickCrypto.createHash('sha256') .update(rawNonce) .digest('hex'); return { rawNonce, nonceDigest }; }; ``` -------------------------------- ### signIn() Method Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Attempts to sign in a user automatically using Google's One-Tap sign-in. It handles automatic sign-in on Android, Apple, and Web platforms. If no saved credential is found, it indicates that a new account creation flow might be needed. The method can be called when the app starts or at a suitable time. ```APIDOC ## `signIn` ### Description Attempts to sign in a user automatically using Google's One-Tap sign-in. This method can be invoked when the application starts or at a suitable moment. It provides automatic sign-in capabilities on Android, Apple, and Web platforms. If no previously signed-in user is detected, the promise resolves with a `NoSavedCredentialFound` object, suggesting a potential call to `createAccount`. ### Signature (`params`?: [`OneTapSignInParams`](api#onetapsigninparams)) => `Promise` ### Platform Behavior * **Android**: Attempts to sign in the user automatically without any interaction, leveraging Google's Credential Manager. * **Apple**: Attempts to restore a previous user sign-in without interaction. * **Web**: Attempts to sign in the user automatically. If no saved credential is found, it presents a sign-in UI. Refer to the web support documentation for more details. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **params** (`OneTapSignInParams`) - Optional - Parameters for the One-Tap sign-in. ### Request Example ```ts import { GoogleOneTapSignIn, statusCodes, isErrorWithCode, isSuccessResponse, isNoSavedCredentialFoundResponse, } from '@react-native-google-signin/google-signin'; const signIn = async () => { try { await GoogleOneTapSignIn.checkPlayServices(); const response = await GoogleOneTapSignIn.signIn(); if (isSuccessResponse(response)) { // read user's info console.log(response.data); } else if (isNoSavedCredentialFoundResponse(response)) { // Android and Apple only. // No saved credential found (user has not signed in yet, or they revoked access) // call `createAccount()` } } catch (error) { console.error(error); if (isErrorWithCode(error)) { switch (error.code) { case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: // Android: play services not available or outdated. // Get more details from `error.userInfo`. // Web: when calling an unimplemented api (requestAuthorization) // or when the Google Client Library is not loaded yet. break; default: // something else happened } } else { // an error that's not related to google sign in occurred } } }; ``` ### Response #### Success Response * **`response.data`** (`object`) - Contains the user's information upon successful sign-in. * **`response`** (`object`) - If no saved credential is found, this object indicates that `createAccount` should be called. #### Response Example ```json { "data": { "id": "104000000000000000000", "name": "John Doe", "givenName": "John", "familyName": "Doe", "email": "john.doe@example.com", "photo": "https://lh3.googleusercontent.com/a-/AOh14G... } } ``` #### Error Response * **`error`** (`object`) - An error object containing details about the failure. * **`code`** (`string`) - The error code (e.g., `statusCodes.PLAY_SERVICES_NOT_AVAILABLE`). * **`userInfo`** (`object`) - Additional information about the error (platform-specific). #### Error Example ```json { "code": "PLAY_SERVICES_NOT_AVAILABLE", "userInfo": { ... } } ``` ``` -------------------------------- ### checkPlayServices Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Checks if the device has the required Google Play Services installed and up-to-date. On Android, it resolves if Play Services are available and meet the minimum version, otherwise it rejects. On Apple, it always resolves as Play Services are not applicable. On Web, it resolves if the Google Client Library is loaded. ```APIDOC ## checkPlayServices ### Description Checks if the device has the required Google Play Services installed and up-to-date. On Android, it resolves if Play Services are available and meet the minimum version, otherwise it rejects. On Apple, it always resolves as Play Services are not applicable. On Web, it resolves if the Google Client Library is loaded. The `showErrorResolutionDialog` parameter (default `true`) controls whether a dialog that helps to resolve an error is shown (only in case the error is user-resolvable). ### Signature `checkPlayServices(showErrorResolutionDialog?: boolean): Promise` ### Parameters #### Query Parameters - **showErrorResolutionDialog** (boolean) - Optional - Controls whether a dialog to resolve user-recoverable errors is shown. ### Response #### Success Response - **PlayServicesInfo** - Information about the Play Services status. ### Request Example ```ts await GoogleOneTapSignIn.checkPlayServices(); ``` ``` -------------------------------- ### Verify Google Play Services availability Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Checks if Google Play Services are installed and up-to-date. Recommended to call this before initiating a sign-in flow. ```javascript try { await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); // google services are available } catch (err) { console.error('play services are not available'); } ``` -------------------------------- ### Configuring Google Sign-In Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Methods for initializing the Google Sign-In module. Call this once at app startup. ```javascript import { GoogleSignin } from '@react-native-google-signin/google-signin'; GoogleSignin.configure(); ``` ```typescript GoogleSignin.configure({ webClientId: '', // client ID of type WEB for your server. Required to get the `idToken` on the user object, and for offline access. scopes: [ /* what APIs you want to access on behalf of the user, default is email and profile this is just an example, most likely you don't need this option at all! */ 'https://www.googleapis.com/auth/drive.readonly', ], offlineAccess: false, // if you want to access Google API on behalf of the user FROM YOUR SERVER hostedDomain: '', // specifies a hosted domain restriction forceCodeForRefreshToken: false, // [Android] related to `serverAuthCode`, read the docs link below *. accountName: '', // [Android] specifies an account name on the device that should be used iosClientId: '', // [iOS] if you want to specify the client ID of type iOS (otherwise, it is taken from GoogleService-Info.plist) googleServicePlistPath: '', // [iOS] if you renamed your GoogleService-Info file, new name here, e.g. "GoogleService-Info-Staging" openIdRealm: '', // [iOS] The OpenID2 realm of the home web server. This allows Google to include the user's OpenID Identifier in the OpenID Connect ID token. profileImageSize: 120, // [iOS] The desired height (and width) of the profile image. Defaults to 120px }); ``` -------------------------------- ### Deploy Website using SSH Source: https://github.com/react-native-google-signin/docs/blob/main/README.md Builds the website and deploys it using SSH. Ensure the USE_SSH environment variable is set. ```bash $ USE_SSH=true yarn deploy ``` -------------------------------- ### Generate Native Project Directories Source: https://github.com/react-native-google-signin/docs/blob/main/docs/setting-up/expo.md Run the prebuild command to generate native project directories for development builds. ```bash npx expo prebuild --clean ``` -------------------------------- ### Handle Account Creation Response Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Initiate account creation and verify if the response indicates a successful sign-in. ```ts const response = await GoogleOneTapSignIn.createAccount(); if (isSuccessResponse(response)) { // handle user signed in } ``` -------------------------------- ### Generate URL-Safe Nonce with Expo Crypto Source: https://github.com/react-native-google-signin/docs/blob/main/docs/security.mdx Generates a URL-safe nonce using `expo-crypto`. This function is useful for security measures like mitigating replay attacks. Ensure `expo-crypto` is installed. ```typescript import * as Crypto from 'expo-crypto'; export function getUrlSafeNonce(byteLength = 32) { if (byteLength < 1) { throw new Error('Byte length must be positive'); } const randomBytes = Crypto.getRandomValues(new Uint8Array(byteLength)); return btoa(String.fromCharCode(...randomBytes)) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/[=]/g, ''); } ``` -------------------------------- ### Create Account with One-Tap Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Use `createAccount` to initiate a flow for signing in or creating a user account for the first time. This is recommended when `signIn` resolves with a `NoSavedCredentialFound` result. ```typescript await GoogleOneTapSignIn.createAccount(); ``` -------------------------------- ### Get Raw Nonce and Nonce Digest with Expo Crypto for Supabase Source: https://github.com/react-native-google-signin/docs/blob/main/docs/security.mdx This function generates both a raw nonce and its SHA-256 digest using `expo-crypto`. The raw nonce is for Supabase's `signInWithIdToken`, and the digest is for the `nonce` parameter in Google Sign-In APIs. Requires `expo-crypto`. ```typescript import { digestStringAsync, CryptoDigestAlgorithm } from 'expo-crypto'; export const getNonce = async () => { // `rawNonce` goes to Supabase's signInWithIdToken(). // Supabase makes a hash of `rawNonce` and compares it with the `nonceDigest` // which is included in the ID token from RN-google-signin. const rawNonce = getUrlSafeNonce(); // `nonceDigest` (SHA-256 hash, hex-encoded) goes to the `nonce` parameter in RN-google-signin APIs const nonceDigest = await digestStringAsync( CryptoDigestAlgorithm.SHA256, rawNonce, ); return { rawNonce, nonceDigest }; }; ``` -------------------------------- ### Run Native App Source: https://github.com/react-native-google-signin/docs/blob/main/docs/setting-up/expo.md Execute the command to run the application on Android and iOS platforms. ```bash npx expo run:android && npx expo run:ios ``` -------------------------------- ### Create Account with Custom Nonce Source: https://github.com/react-native-google-signin/docs/blob/main/docs/security.mdx Use this snippet to create an account with a custom nonce for enhanced security. Ensure `getUrlSafeNonce()` is implemented correctly. ```typescript const response = await GoogleOneTapSignIn.createAccount({ nonce: getUrlSafeNonce(), }); ``` -------------------------------- ### createAccount Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Initiates a flow to sign in a user for the first time, creating an account if necessary. It presents a list of available Google accounts on the device for the user to choose from. This method is suitable for use when no saved credentials are found. ```APIDOC ## createAccount ### Description Initiates a flow to sign in a user for the first time, creating an account if necessary. It presents a list of available Google accounts on the device for the user to choose from. This method is suitable for use when no saved credentials are found. ### Signature (`params`?: `OneTapCreateAccountParams`) => `Promise`<`OneTapResponse`> ### Platforms * **Android**: Starts a flow to sign in with your app for the first time (to create a user account). It offers a list of user accounts to choose from (multiple Google accounts can be logged in on the device). * **Apple**: Starts an interactive sign-in flow. Offers a list of user accounts to choose from (multiple Google accounts can be logged in on the device). * **Web**: Presents a one-tap prompt and waits for user interaction (it will not sign in automatically). The prompt has a slightly different styling than with `signIn` (configurable via the `context` param). ### Usage ```ts await GoogleOneTapSignIn.createAccount(); ``` ``` -------------------------------- ### Build Static Website Content Source: https://github.com/react-native-google-signin/docs/blob/main/README.md Generates the static content for the website, typically placed in the 'build' directory, ready for hosting. ```bash $ yarn build ``` -------------------------------- ### Complete Sign-In Flow Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx This snippet demonstrates a full sign-in process using Google One-Tap. It includes checking for existing credentials, creating new accounts, and handling explicit sign-in if necessary. Ensure `GoogleOneTapSignIn.configure()` is called early in your app's lifecycle. ```tsx import { GoogleOneTapSignIn, GoogleLogoButton, } from '@react-native-google-signin/google-signin'; ; export const startSignInFlow = async () => { try { GoogleOneTapSignIn.configure(); // move this to after your app starts await GoogleOneTapSignIn.checkPlayServices(); const signInResponse = await GoogleOneTapSignIn.signIn(); if (signInResponse.type === 'success') { // use signInResponse.data } else if (signInResponse.type === 'noSavedCredentialFound') { // the user wasn't previously signed into this app const createResponse = await GoogleOneTapSignIn.createAccount(); if (createResponse.type === 'success') { // use createResponse.data } else if (createResponse.type === 'noSavedCredentialFound') { // no Google user account was present on the device yet (unlikely but possible) const explicitResponse = await GoogleOneTapSignIn.presentExplicitSignIn(); if (explicitResponse.type === 'success') { // use explicitResponse.data } } } // the else branches correspond to the user canceling the sign in } catch (error) { // handle error } }; ``` -------------------------------- ### Deploy Website without SSH Source: https://github.com/react-native-google-signin/docs/blob/main/README.md Builds the website and deploys it without using SSH. Replace with your actual GitHub username. ```bash $ GIT_USER= yarn deploy ``` -------------------------------- ### GoogleSignin.configure Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Configures the Google Sign-In module. This must be called once before any other sign-in methods. ```APIDOC ## GoogleSignin.configure ### Description Initializes the Google Sign-In module with the provided options. This method is synchronous and mandatory before calling signIn or signInSilently. ### Parameters #### Request Body - **webClientId** (string) - Optional - Client ID of type WEB for your server. - **scopes** (array) - Optional - List of Google API scopes to access. - **offlineAccess** (boolean) - Optional - Enables offline access to Google APIs. - **hostedDomain** (string) - Optional - Restricts sign-in to a specific hosted domain. - **forceCodeForRefreshToken** (boolean) - Optional - [Android] Forces the return of a refresh token. - **accountName** (string) - Optional - [Android] Specifies an account name on the device. - **iosClientId** (string) - Optional - [iOS] Specifies the iOS client ID. - **googleServicePlistPath** (string) - Optional - [iOS] Custom path for the GoogleService-Info file. - **openIdRealm** (string) - Optional - [iOS] The OpenID2 realm of the home web server. - **profileImageSize** (number) - Optional - [iOS] Desired height and width of the profile image. ### Request Example { "webClientId": "", "scopes": ["https://www.googleapis.com/auth/drive.readonly"] } ``` -------------------------------- ### Bun Package Manager Configuration Source: https://github.com/react-native-google-signin/docs/blob/main/docs/install.mdx Configure Bun to use the GitHub npm packages registry by creating a bunfig.toml file. This specifies the registry URL and authentication token for scoped packages. ```toml [install.scopes] "@react-native-google-signin" = { url = "https://npm.pkg.github.com/", token = "$NPM_TOKEN_GOOGLE_SIGN_IN" } ``` -------------------------------- ### Implement WebGoogleSigninButton Source: https://github.com/react-native-google-signin/docs/blob/main/docs/buttons/web.mdx Basic implementation of the sign-in button component for web applications. ```tsx import { WebGoogleSigninButton } from '@react-native-google-signin/google-signin'; ; ``` -------------------------------- ### ConfigureParams Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Parameters for configuring Google Sign-In. These options allow customization of the sign-in process, including account prioritization, hosted domain restrictions, offline access, and scope requests. ```APIDOC ## ConfigureParams ### Description Parameters for configuring Google Sign-In. ### Type Declaration - **ClientIdOrPlistPath** (string) - Required - The client ID or Plist path. - **accountName?** (string) - Optional - Android only. An account name that should be prioritized. - **forceCodeForRefreshToken?** (boolean) - Optional - Android only. Only set to `true` if your server has suffered some failure and lost the user's refresh token. - **hostedDomain?** (string) - Optional - Specifies a hosted domain restriction. By setting this, authorization will be restricted to accounts of the user in the specified domain. - **offlineAccess?** (boolean) - Optional - Must be `true` if you wish to access user APIs on behalf of the user from your own server. When offline access is requested, an authorization code is returned so the server can use the authorization code to exchange for access token and refresh token. The access token allows the server to access Google data on behalf of the user. - **openIdRealm?** (string) - Optional - iOS only. The OpenID2 realm of the home web server. This allows Google to include the user's OpenID Identifier in the OpenID Connect ID token. - **profileImageSize?** (number) - Optional - iOS only. The desired height and width of the profile image. Default: `120px`. - **scopes?** (string[]) - Optional - The Google API scopes to request access to. Default: `["email", "profile"]`. - **webClientId?** (string) - Optional - The web client ID obtained from Google Cloud console. Required for offline access. ``` -------------------------------- ### Run Config Doctor with APK File Source: https://github.com/react-native-google-signin/docs/blob/main/docs/config-doctor.mdx Use this command to extract SHA-1 fingerprints from a local APK file. Requires the path to the APK. ```bash npx @react-native-google-signin/config-doctor --apk-path ./app-release.apk ``` -------------------------------- ### Configure and Initiate Google One-Tap Sign-In on Web Source: https://github.com/react-native-google-signin/docs/blob/main/docs/web-support.mdx This snippet configures the Google One-Tap Sign-In client with your web client ID and initiates the sign-in process. It handles success and error responses, and optionally listens for important events. Use this on page load for a seamless user experience. ```typescript useEffect(() => { GoogleOneTapSignIn.configure({ webClientId, iosClientId: config.iosClientId, }); if (Platform.OS === 'web') { GoogleOneTapSignIn.signIn( { ux_mode: 'popup', }, { onResponse: (response) => { if (response.type === 'success') { console.log(response.data); } }, onError: (error) => { // handle error }, momentListener: (moment) => { console.log('moment', moment); }, }, ); } }, []); ``` -------------------------------- ### iOS Configuration: ClientIdOrPlistPath Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Defines the configuration options for iOS Google Sign-In, allowing either an explicit client ID or a custom plist path. ```APIDOC ## ClientIdOrPlistPath ### Description Configures the iOS client ID for Google Sign-In. By default, it uses the GoogleService-Info.plist file, but can be overridden. ### Parameters #### Request Body - **iosClientId** (string) - Optional - Explicitly set the iOS client ID. - **googleServicePlistPath** (string) - Optional - Specify a custom bundle path name for the Firebase config file (e.g., "GoogleService-Info-Staging"). ``` -------------------------------- ### SignInParams Configuration Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Defines the parameters used when initiating a sign-in request. ```APIDOC ## SignInParams ### Description Configuration object for sign-in requests, including platform-specific hints and security tokens. ### Parameters - **loginHint** (string) - Optional - iOS only. The user's ID or email address to prefill in the UI. - **nonce** (string) - Optional - iOS only. A cryptographically random value used to mitigate replay attacks. ``` -------------------------------- ### GoogleSignin.signIn Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Prompts the user to sign in via a modal and returns the user information. ```APIDOC ## GoogleSignin.signIn ### Description Displays a modal to the user to perform the Google sign-in process. Returns a promise that resolves with the user's sign-in response or rejects on error. ### Response #### Success Response (200) - **data** (object) - The user information object returned upon successful authentication. #### Response Example { "data": { "user": { "email": "user@example.com", "name": "John Doe" }, "idToken": "..." } } ``` -------------------------------- ### Web Universal Sign-In Callbacks Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Defines the callback structure for handling sign-in results on the web, which uses callbacks instead of promises. ```APIDOC ## WebOneTapSignInCallbacks ### Description Defines the interface for web sign-in callbacks. Results are delivered via these callbacks rather than promises. ### Parameters #### Request Body - **momentListener** (MomentListener) - Optional - Listener for sign-in moments. - **onError** (function) - Required - Callback function triggered on error, receiving a NativeModuleError. - **onResponse** (function) - Required - Callback function triggered on success, receiving a OneTapExplicitSignInResponse. ``` -------------------------------- ### presentExplicitSignIn Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Presents the sign-in dialog explicitly. This is useful when no Google account is present on the device, prompting the user to add one. It is preferably called as a reaction to a user tapping a sign-in button. ```APIDOC ## presentExplicitSignIn ### Description Presents the sign-in dialog explicitly. This is useful when no Google account is present on the device, prompting the user to add one. It is preferably called as a reaction to a user tapping a sign-in button. ### Signature (`params`?: `OneTapExplicitSignInParams`) => `Promise`<`OneTapExplicitSignInResponse`> ### Platforms * **Android**: Presents the sign in dialog explicitly. This is useful if both `signIn` and `createAccount` resolve with [`NoSavedCredentialFound`](api#nosavedcredentialfound) object - which happens (in the unlikely case) when no Google account is present on the device. This prompts the user to add a Google account. * **Apple**: Starts an interactive sign-in flow. Same as `createAccount`. * **Web**: Presents a one-tap prompt. Same as `createAccount`. ### Usage ```ts await GoogleOneTapSignIn.presentExplicitSignIn(); ``` ``` -------------------------------- ### Type Declarations for Google Sign-In Methods Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx This section outlines the type declarations for various methods available in the Google Sign-In library, including their parameters and return types. ```APIDOC ## Type Declarations | Name | Type | | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `addScopes()` | (`options`: [`AddScopesParams`](#addscopesparams)) => `Promise`\<[`SignInResponse`](#signinresponse) \| `null`\> | | `clearCachedAccessToken()` | (`tokenString`: `string`) => `Promise`\<`null`\> | | `configure()` | (`options?`: [`ConfigureParams`](#configureparams)) => `void` | | `enableAppCheck()` | (`params?`: [`EnableAppCheckParams`](#enableappcheckparams)) => `Promise`\<`null`\> | | `getCurrentUser()` | () => [`User`](#user) \| `null` | | `getTokens()` | () => `Promise`\<[`GetTokensResponse`](#gettokensresponse)\ | `hasPlayServices()` | (`options?`: [`HasPlayServicesParams`](#hasplayservicesparams)) => `Promise`\<`boolean`\> | | `hasPreviousSignIn()` | () => `boolean` | | `revokeAccess()` | () => `Promise`\<`null`\> | | `signIn()` | (`options`: [`SignInParams`](#signinparams)) => `Promise`\<[`SignInResponse`](#signinresponse)\ | `signInSilently()` | () => `Promise`\<[`SignInSilentlyResponse`](#signinsilentlyresponse)\ | `signOut()` | () => `Promise`\<`null`\> | ``` -------------------------------- ### Run Config Doctor with Device/Emulator Source: https://github.com/react-native-google-signin/docs/blob/main/docs/config-doctor.mdx Use this command to extract SHA-1 fingerprints from a connected device or emulator. Requires the app's package name. ```bash npx @react-native-google-signin/config-doctor --package-name com.yourapp.name ``` -------------------------------- ### Google Sign-In Configuration Properties Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Configuration properties for handling authentication events, errors, and user responses. ```APIDOC ## Google Sign-In Configuration Properties ### Description These properties are used to configure callbacks for the Google Sign-In process, including event monitoring, error handling, and response processing. ### Properties - **momentListener** (MomentListener) - Optional - A callback function that is called when important events take place. - **onError** ((error: NativeModuleError) => void | Promise) - Required - Called when an error occurs. The error object contains a code property to determine the reason for the failure. - **onResponse** ((userInfo: OneTapExplicitSignInResponse) => void | Promise) - Required - Called when the user successfully signs in or cancels the sign-in process via web One-tap or button flow. ``` -------------------------------- ### Run Configuration Doctor Source: https://github.com/react-native-google-signin/docs/blob/main/docs/troubleshooting.mdx Use this command-line tool to diagnose and fix configuration mismatches between your app and the Google Cloud/Firebase console. It's recommended when encountering `DEVELOPER_ERROR` or related messages. ```bash npx @react-native-google-signin/config-doctor ``` -------------------------------- ### Adding additional scopes Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Requesting extra permissions after the initial configuration. ```javascript const response = await GoogleSignin.addScopes({ scopes: ['https://www.googleapis.com/auth/user.gender.read'], }); ``` -------------------------------- ### Update signIn Method for Universal Sign In Source: https://github.com/react-native-google-signin/docs/blob/main/docs/migrating.md This snippet shows the changes needed for the `signIn` method to adapt to the new Universal Sign-In API. It highlights the shift from direct `userInfo` access to `response.data` and the new success/error handling. ```diff const signIn = async () => { try { - const userInfo = await GoogleOneTapSignIn.signIn({ - webClientId: `autoDetect`, // works only if you use Firebase - iosClientId: config.iosClientId, // only needed if you're not using Firebase - }); - setState({ userInfo }); // use e.g. `userInfo.name` + const response = await GoogleOneTapSignIn.signIn(); + + if (response.type === 'success') { + setState({ userInfo: response.data }); + } else if (response.type === 'noSavedCredentialFound') { + // Android and Apple only. No saved credential found, call `createAccount` + } } catch (error) { if (isErrorWithCode(error)) { switch (error.code) { - case statusCodes.NO_SAVED_CREDENTIAL_FOUND: - // Android and Apple only. No saved credential found, call `createAccount` - break; - case statusCodes.SIGN_IN_CANCELLED: - // sign in was cancelled - break; - case statusCodes.ONE_TAP_START_FAILED: - // Android-only, you probably have hit rate limiting. - // On Android, you can still call `presentExplicitSignIn` in this case. - break; case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: // Android-only: play services not available or outdated // Web: when calling an unimplemented api (requestAuthorization) break; default: // something else happened } } else { // an error that's not related to google sign in occurred } } }; ``` -------------------------------- ### Configure Google One-Tap Sign-In Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Call this method to initialize the Google One-Tap sign-in. It's mandatory before using other sign-in methods. `webClientId` is required, and can be set to 'autoDetect'. Provide `iosClientId` if not using Expo or Firebase. ```typescript GoogleOneTapSignIn.configure({ webClientId: 'autoDetect', }); ``` -------------------------------- ### GoogleOneTapSignIn Methods Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Core methods for configuring, signing in, and managing user sessions via Google One Tap. ```APIDOC ## GoogleOneTapSignIn.configure ### Description Configures the Google One Tap sign-in instance with the provided parameters. ### Parameters #### Request Body - **options** (OneTapConfigureParams) - Required - Configuration options for the sign-in instance. ## GoogleOneTapSignIn.signIn ### Description Initiates the sign-in process. ### Parameters #### Request Body - **params** (OneTapSignInParams) - Optional - Parameters for the sign-in request. ### Response #### Success Response (200) - **response** (OneTapResponse) - The result of the sign-in operation. ## GoogleOneTapSignIn.signOut ### Description Signs the user out of the current session. ### Response #### Success Response (200) - **result** (null) - Returns null upon successful sign-out. ``` -------------------------------- ### GoogleSigninButton Component Source: https://github.com/react-native-google-signin/docs/blob/main/docs/buttons/native.md The GoogleSigninButton component renders a native sign-in button that automatically handles localization. ```APIDOC ## GoogleSigninButton Component ### Description A native sign-in button component for iOS and Android that supports automatic localization. It renders null on web and a simplified version on macOS. ### Props - **size** (enum) - Optional - Determines button dimensions. Values: `Size.Icon`, `Size.Standard`, `Size.Wide`. Default: `Size.Standard`. - **color** (enum) - Optional - Determines button background color. Values: `Color.Dark`, `Color.Light`. - **disabled** (boolean) - Optional - If true, disables all button interactions. - **onPress** (function) - Required - Handler called when the button is tapped. ### Request Example ```tsx { /* initiate sign in */ }} disabled={isInProgress} /> ``` ``` -------------------------------- ### Apply Roboto Font to GoogleLogoButton Source: https://github.com/react-native-google-signin/docs/blob/main/docs/buttons/google-logo-button.mdx Configuring the textStyle prop to use the required Roboto font for branding compliance. ```tsx ``` -------------------------------- ### Importing Google Sign-In components Source: https://github.com/react-native-google-signin/docs/blob/main/docs/original.mdx Required imports for accessing the GoogleSignin module, button, and status codes. ```typescript import { GoogleSignin, GoogleSigninButton, statusCodes, } from '@react-native-google-signin/google-signin'; ``` -------------------------------- ### Implement GoogleLogoButton in a Screen Source: https://github.com/react-native-google-signin/docs/blob/main/docs/buttons/google-logo-button.mdx Basic implementation of the GoogleLogoButton component within a React Native screen. ```tsx import { GoogleLogoButton } from '@react-native-google-signin/google-signin'; function SignInScreen() { return ( { // Handle sign in }} label="Sign in with Google" textStyle={{ fontFamily: 'Roboto' }} /> ); } ``` -------------------------------- ### Render GoogleSigninButton Source: https://github.com/react-native-google-signin/docs/blob/main/docs/buttons/native.md Use this component to display the native Google sign-in button. It supports different sizes and colors, and handles the onPress event for initiating sign-in. The button can be disabled by passing a boolean to the `disabled` prop. ```tsx import { GoogleSigninButton } from '@react-native-google-signin/google-signin'; { // initiate sign in }} disabled={isInProgress} />; ``` -------------------------------- ### OneTapConfigureParams Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Configuration parameters for the One Tap sign-in flow, including web client ID, scopes, and logging. ```APIDOC ## OneTapConfigureParams > **OneTapConfigureParams** = [`ClientIdOrPlistPath`](#clientidorplistpath) & { `hostedDomain?`: `string`; `logLevel?`: "debug" | "info" | "warn"; `openIdRealm?`: `string`; `profileImageSize?`: `number`; `scopes?`: `string`[]; `webClientId`: `WebClientId`; } `webClientId` is the most important parameter in the configuration. It is required. ### Type Declaration | Name | Type | Description | | ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `hostedDomain?` | `string` | iOS only. Specifies a hosted domain restriction. By setting this, authorization will be restricted to accounts of the user in the specified domain. | | `logLevel?` | "debug" | "info" | "warn" | Web only. Controls debug logging in browser console. This is implemented in Google's web SDK and is not part of their public API so it may change or be removed at any time. | | `openIdRealm?` | `string` | iOS only. The OpenID2 realm of the home web server. This allows Google to include the user's OpenID Identifier in the OpenID Connect ID token. | | `profileImageSize?` | `number` | iOS only. The desired height and width of the profile image. **Default** `120px` | | `scopes?` | `string`[] | iOS only. The Google API scopes to request access to. Use `requestAuthorization` to request additional scopes on Android. **Default** `["email", "profile"]` | | `webClientId` | `WebClientId` | The web client ID obtained from Google Cloud console. In the Universal module only, pass `autoDetect` to automatically determine the value from Firebase config file. | ``` -------------------------------- ### GoogleOneTapSignIn Utility Methods Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Utility methods for checking Play Services, revoking access, and managing tokens. ```APIDOC ## GoogleOneTapSignIn.checkPlayServices ### Description Checks the status of Google Play Services. ### Parameters #### Request Body - **showErrorResolutionDialog** (boolean) - Optional - Whether to show a dialog to resolve errors. ### Response #### Success Response (200) - **info** (PlayServicesInfo) - Information regarding Play Services status. ## GoogleOneTapSignIn.revokeAccess ### Description Revokes access for a specific user. ### Parameters #### Request Body - **emailOrUniqueId** (string) - Required - The email or unique ID of the user to revoke access for. ``` -------------------------------- ### Present Explicit Sign-In Source: https://github.com/react-native-google-signin/docs/blob/main/docs/one-tap.mdx Call `presentExplicitSignIn` to explicitly show the sign-in dialog. This is useful when both `signIn` and `createAccount` fail to find credentials, prompting the user to add a Google account. It's preferably called in response to a user tapping a sign-in button. ```typescript await GoogleOneTapSignIn.presentExplicitSignIn(); ``` -------------------------------- ### Update signInSilently for Original Sign In Source: https://github.com/react-native-google-signin/docs/blob/main/docs/migrating.md This snippet demonstrates the necessary modifications for the `signInSilently` method when migrating from older versions. It shows how to handle the new success and `noSavedCredentialFound` response types, replacing the old `SIGN_IN_REQUIRED` error handling. ```diff const getCurrentUserInfo = async () => { try { const response = await GoogleSignin.signInSilently(); + if (isSuccessResponse(response)) { + setState({ userInfo: response.data }) + } else if (isNoSavedCredentialFoundResponse(response)) { + // user has not signed in yet + } - setState({ userInfo: response }); } catch (error) { - if (error.code === statusCodes.SIGN_IN_REQUIRED) { - // user has not signed in yet - } else { - // some other error - } } }; ``` -------------------------------- ### SignInSuccessResponse Structure Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Describes the object returned upon a successful authentication event. ```APIDOC ## SignInSuccessResponse ### Description The response object returned when the user successfully signs in. ### Response - **data** (User) - The user details object. - **type** ("success") - The status type of the response. ### User Object - **idToken** (string | null) - The ID token. - **scopes** (string[]) - List of granted scopes. - **serverAuthCode** (string | null) - The server authentication code. - **user** (object) - User profile information including email, familyName, givenName, id, name, and photo. ``` -------------------------------- ### Google Sign-In Response Properties Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx This section describes the properties returned by the Google Sign-In process, which include user details and authentication information. ```APIDOC ## Google Sign-In Response Properties ### Description This details the structure of the response object received after a successful Google Sign-In. ### Method N/A (This describes a response object, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **credentialOrigin** (CredentialResponse["select_by"]) - The credential origin. This is the method that was used to sign in the user. On native platforms, this is always "user". On the web it's a value from a union type. - **idToken** (string) - The ID token for the authenticated user. - **serverAuthCode** (string | null) - iOS only. Not null only if a valid `webClientId` and `offlineAccess: true` was specified in `configure()`. Call `requestAuthorization()` to obtain it on Android. - **user** (object) - An object containing the user's profile information. - **user.email** (string | null) - The user's email address. - **user.familyName** (string | null) - The user's family name. - **user.givenName** (string | null) - The user's given name. - **user.id** (string) - An immutable identifier for the user. Unique among all Google accounts and never reused (user's email can change, this value cannot). - **user.name** (string | null) - The user's full name. - **user.phoneNumber** (string | null) - The user's phone number. - **user.photo** (string | null) - The URL to the user's profile picture. #### Response Example ```json { "credentialOrigin": "user", "idToken": "your_id_token_here", "serverAuthCode": null, "user": { "email": "user@example.com", "familyName": "Doe", "givenName": "John", "id": "1234567890", "name": "John Doe", "phoneNumber": null, "photo": "https://example.com/photo.jpg" } } ``` ``` -------------------------------- ### Handle Google One Tap Sign-In Source: https://github.com/react-native-google-signin/docs/blob/main/docs/api/index.mdx Initiate the One Tap sign-in process and check for the absence of saved credentials. ```ts const response = await GoogleOneTapSignIn.signIn(); if (isNoSavedCredentialFoundResponse(response)) { // the case when no user was previously signed in } ``` -------------------------------- ### Handle URL schemes in AppDelegate (Objective-C) Source: https://github.com/react-native-google-signin/docs/blob/main/docs/setting-up/ios.md Implement the application openURL method in your Objective-C AppDelegate to support multiple URL listeners. ```objc #import "AppDelegate.h" #import // ⬅️ add the header import // … @implementation AppDelegate // … // ⬇️ Add this method before file @end - (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary *)options { // Add any other URL handlers you're using (e.g. Facebook SDK) return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options] || [GIDSignIn.sharedInstance handleURL:url]; } @end ```