Expo

Documentation

GoogleSignIn

This library provides native Google authentication for standalone Expo apps or bare React Native apps. It cannot be used in the Expo client as the native GoogleSignIn library expects your REVERSE_CLIENT_ID in the info.plist at build-time. To use Google authentication in the Expo client, check out Google or AppAuth.
Platform Compatibility
Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

For managed apps, you'll need to run expo install expo-google-sign-in. To use it in a bare React Native app, follow its installation instructions. For a more in-depth guide, check out this blog post!

import * as GoogleSignIn from 'expo-google-sign-in';

For questions on setup, feel free to comment on this post: React Native Google Sign-Up
  1. Go to your app.json and make sure you define your ios.bundleIdentifier and the android.package you want to use.
  2. Open up the Firebase Console and setup a new project, or use an existing one.
  3. Create a native iOS, and Android app using the Bundle ID and Android package you defined earlier.
  4. Download the GoogleService-info.plist (iOS) & the google-services.json (Android). Move them to your Expo project.
  5. In the app.json, set your expo.ios.config.googleSignIn.reservedClientId to the value of REVERSE_CLIENT_ID in the GoogleService-info.plist.
  6. Also in app.json, set expo.android.googleServicesFile to the relative path of your google-services.json. Make sure the file is located somewhere in your Expo project.
 // app.json
{
  "expo": {
    "ios": {
      // The bundle ID you used with your Firebase app
      "bundleIdentifier": "example.expo.googlesignin",
      "config": {
        "googleSignIn": {
          // Your REVERSE_CLIENT_ID from the GoogleService-info.plist
          "reservedClientId": "<YOUR_IOS_CLIENT_ID>"
        }
      }
    },
    "android": {
        // The package you used with your Firebase app
        "package": "example.expo.googlesignin",
        // Relative path to the file generated by Firebase
        "googleServicesFile": "./google-services.json"
    }
  }
}
At this point you can build your project and upload it to the App Store or the Google Play Store.
When your app is built you can verify that the iOS URL Scheme is properly set up by reading it using the expo-app-auth module in a standalone app.
import { AppAuth } from 'expo-app-auth';

// This value should contain your REVERSE_CLIENT_ID
const { URLSchemes } = AppAuth;

Before using the API we first need to call GoogleSignIn.initAsync({ ... }) which configures how sign in functionality will work.
try {
  await GoogleSignIn.initAsync({ clientId: '<YOUR_IOS_CLIENT_ID>' });
} catch ({ message }) {
  alert('GoogleSignIn.initAsync(): ' + message);
}

signInAsync = async () => {
  try {
    await GoogleSignIn.askForPlayServicesAsync();
    const { type, user } = await GoogleSignIn.signInAsync();
    if (type === 'success') {
      // ...
    }
  } catch ({ message }) {
    alert('login: Error:' + message);
  }
};

signOutAsync = async () => {
  try {
    await GoogleSignIn.signOutAsync();
    this.setState({ user: null });
  } catch ({ message }) {
    alert('signOutAsync: ' + message);
  }
};

Android Only, this method always returns true on iOS
Use this method to determine if a user's device can utilize Google Sign-In functionality. By default this method will assume the option is false and silently check for Play Services, whereas passing true will present a modal if the Play Services aren't available, prompting the user to update Play Services.

Android Only, this method always returns true on iOS
A convenience wrapper for getPlayServiceAvailability(true), this method will present a modal for the user to update Play Services if they aren't already up-to-date.
Returns true after the user successfully updates.

Configures how the GoogleSignIn module will attempt to sign in. You can call this method multiple times.
See all the available options under the GoogleSignInOptions type.

Asynchronously returns a boolean representing the user's authentication status.

This method will attempt to reauthenticate the user without initializing the authentication flow. If the method is successful, the currently authenticated GoogleUser will be returned, otherwise the method will return null.
On Android, the returned GoogleUser object may have a nonnull serverAuthCode rather than a refreshToken. If you need a refresh token, you can call Google's API directly to exchange the authorization code for a token. Instructions for how to perform this request can be found in Google's documentation ("Step 5: Exchange authorization code for refresh and access tokens"). The clientId in these requests is the Web Client ID from the Google API Console.

Starts the native authentication flow with the information provided in initAsync(). If a user cancels, the method will return { type: 'cancel', user: null }. However if a user successfully finishes the authentication flow, the returned value will be: { type: 'success', user: GoogleUser }.
There are some errors that can be thrown while authenticating, check GoogleSignIn.ERRORS for available error codes.

Signs out the currently authenticated user. Unlike disconnectAsync(), this method will not revoke the access token. This means you can specify the accountName and reauthenticate without extra user approval.

Returns true if a user is authenticated and the access token has not been invalidated.

Signs out the current user and revokes the access tokens associated with the account. This will prevent reauthentication, whereas signOutAsync() will not.

If a user is authenticated, this method will return all the basic profile information in the form of a GoogleUser.

Get the most recent instance of the authenticated GoogleUser.

Returns an image URI for the currently authenticated user. This method will return null if no user is signed in, or if the current user doesn't have a profile image on Google. The default size is 128px, if the requested image size is larger than the original image size, the full sized image will be returned.

/* Android Only */
type GoogleSignInType = 'default' | 'games';
type GoogleSignInOptions = {
  /*
   * [iOS][Android][optional]: `accountName: ?string`
   * [default]: `[GoogleSignIn.SCOPES.PROFILE, GoogleSignIn.SCOPES.EMAIL]`
   * Pass the scopes you wish to have access to.
   */
  scopes: ?Array<string>,

  /*
   * [iOS][Android][optional]: `webClientId: ?string`
   * [default]: `undefined`
   * The client ID of the home web server.  This will be returned as the |audience| property of the
   * OpenID Connect ID token.  For more info on the ID token:
   * https://developers.google.com/identity/sign-in/ios/backend-auth
   */
  webClientId: ?string,

  /*
   * [iOS][Android][optional]: `hostedDomain: ?string`
   * [default]: `undefined`
   * The hosted G Suite domain of the user. Provided only if the user belongs to a hosted domain.
   */
  hostedDomain: ?string,

  /*
   * [iOS][Android][optional]: `accountName: ?string`
   * [default]: `undefined`
   * If you know the user's email address ahead of time, you can add it here and it will be the default option
   * if the user has approved access for this app, the Auth will return instantly.
   */
  accountName: ?string,

  /*
   * [Android][optional]: `signInType?: GoogleSignIn.TYPES.DEFAULT | GoogleSignIn.TYPES.GAMES`
   * [default]: `undefined`
   * The service you wish to sign in to
   * GoogleSignIn.TYPES.DEFAULT | GoogleSignIn.TYPES.GAMES
   */
  signInType: ?GoogleSignInType,

  /*
   * [Android][optional]: `isOfflineEnabled: ?boolean`
   * [default]: `undefined`
   * If true, the server will return refresh tokens that can be used to access data when the user has unauthenticated.
   * 1. Safely secure the refresh token as you can only get one during the initial auth flow.
   * 2. There are only so many refresh tokens that are issued, limit per user/app, you can also get one for a single user across all clients in an app. If you requests too many tokens, older tokens will begin to be invalidated.
   */
  isOfflineEnabled: ?boolean,

  /*
   * [Android][optional]: `isPromptEnabled: ?boolean`
   * [default]: false
   * Forces the consent prompt to be shown everytime a user authenticates. Enable this only when necessary.
   */
  isPromptEnabled: ?boolean,

  /*
   * [iOS][optional]: `clientId: ?string`
   * [default]: Read from GoogleService-info.plist `CLIENT_ID` on iOS, and google-services.json `oauth_client.client_id` on Android.
   * The client ID of the app from the Google APIs (or Firebase) console, this must be set for sign in to work.
   * This value must be defined in the google-services.json on Android, you can define your custom google-services.json
   */
  clientId: ?string,

  /*
   * [iOS][optional]: `language: ?string`
   * [default]: `undefined`
   * The language for sign in, in the form of ISO 639-1 language code optionally followed by a dash
   * and ISO 3166-1 alpha-2 region code, such as |@"it"| or |@"pt-PT"|. Only set if different from
   * system default.
   */
  language: ?string,

  /*
   * [iOS][optional]: `openIdRealm?: ?string`
   * [default]: `undefined`
   * The OpenID2 realm of the home web server. This allows Google to include the user's OpenID
   * Identifier in the OpenID Connect ID token..
   */
  openIdRealm: ?string,
};
type GoogleSignInAuthResultType = 'success' | 'cancel';
type GoogleSignInAuthResult = {
  type: GoogleSignInAuthResultType,
  user: ?User,
};

The base class for GoogleSignIn authentication data. This method enables you to compare and serialize objects.
Methods:
  • equals(other: ?any): boolean
  • toJSON(): object

Extends GoogleAuthData, core management of user data.
Variables:
  • uid: string;
  • email: string;
  • displayName: ?string;
  • photoURL: ?string;
  • firstName: ?string;
  • lastName: ?string;

Extends GoogleIdentity, manaages all data regarding an authenticated user.
Variables:
  • auth: ?Authentication;
  • scopes: Array<string>;
  • hostedDomain: ?string;
  • serverAuthCode: ?string;
Methods:
  • clearCache(): void
  • getHeaders(): Promise<{ [string]: string }>
  • refreshAuth(): Promise<?GoogleAuthentication>

Extends GoogleAuthData, manages the user tokens.
Variables:
  • clientId: ?string;
  • accessToken: ?string;
  • accessTokenExpirationDate: ?number;
  • refreshToken: ?string;
  • idToken: ?string;
  • idTokenExpirationDate: ?number; | UNIX time in milliseconds

All of the available authentication error codes.
  • GoogleSignIn.ERRORS.SIGN_IN_CANCELLED The user has cancelled the auth flow
  • GoogleSignIn.ERRORS.SIGN_IN_REQUIRED Attempting to access user data before any user has been authenticated
  • GoogleSignIn.ERRORS.TASK_IN_PROGRESS An existing auth task is already running.
  • GoogleSignIn.ERRORS.SIGN_IN_EXCEPTION A general error has occurred
  • GoogleSignIn.ERRORS.SIGN_IN_FAILED A Play Services error has occured (Android only)
  • GoogleSignIn.ERRORS.INVALID_ACCOUNT An invalid account has been provided with accountName (Android only)
  • GoogleSignIn.ERRORS.SIGN_IN_NETWORK_ERROR An issue with the internet connection has caused the auth task to fail (Android only)

  • GoogleSignIn.SCOPES.PROFILE
  • GoogleSignIn.SCOPES.EMAIL
  • GoogleSignIn.SCOPES.OPEN_ID
  • GoogleSignIn.SCOPES.PLUS_ME
  • GoogleSignIn.SCOPES.GAMES
  • GoogleSignIn.SCOPES.GAMES_LITE
  • GoogleSignIn.SCOPES.CLOUD_SAVE
  • GoogleSignIn.SCOPES.APP_STATE
  • GoogleSignIn.SCOPES.DRIVE_FILE
  • GoogleSignIn.SCOPES.DRIVE_APPFOLDER
  • GoogleSignIn.SCOPES.DRIVE_FULL
  • GoogleSignIn.SCOPES.DRIVE_APPS
  • GoogleSignIn.SCOPES.FITNESS_ACTIVITY_READ
  • GoogleSignIn.SCOPES.FITNESS_ACTIVITY_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_LOCATION_READ
  • GoogleSignIn.SCOPES.FITNESS_LOCATION_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_BODY_READ
  • GoogleSignIn.SCOPES.FITNESS_BODY_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_NUTRITION_READ
  • GoogleSignIn.SCOPES.FITNESS_NUTRITION_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_BLOOD_PRESSURE_READ
  • GoogleSignIn.SCOPES.FITNESS_BLOOD_PRESSURE_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_BLOOD_GLUCOSE_READ
  • GoogleSignIn.SCOPES.FITNESS_BLOOD_GLUCOSE_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_OXYGEN_SATURATION_READ
  • GoogleSignIn.SCOPES.FITNESS_OXYGEN_SATURATION_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_BODY_TEMPERATURE_READ
  • GoogleSignIn.SCOPES.FITNESS_BODY_TEMPERATURE_READ_WRITE
  • GoogleSignIn.SCOPES.FITNESS_REPRODUCTIVE_HEALTH_READ
  • GoogleSignIn.SCOPES.FITNESS_REPRODUCTIVE_HEALTH_READ_WRITE

All of the available sign in types.
  • GoogleSignIn.TYPES.DEFAULT The standard login method.
  • GoogleSignIn.TYPES.GAMES Sign in to Google Play Games (Android only)

import React from 'react';
import { Text } from 'react-native';
import { GoogleSignIn } from 'expo-google-sign-in';

export default class AuthScreen extends React.Component {
  state = { user: null };

  componentDidMount() {
    this.initAsync();
  }

  initAsync = async () => {
    await GoogleSignIn.initAsync({
      clientId: '<YOUR_IOS_CLIENT_ID>',
    });
    this._syncUserWithStateAsync();
  };

  _syncUserWithStateAsync = async () => {
    const user = await GoogleSignIn.signInSilentlyAsync();
    this.setState({ user });
  };

  signOutAsync = async () => {
    await GoogleSignIn.signOutAsync();
    this.setState({ user: null });
  };

  signInAsync = async () => {
    try {
      await GoogleSignIn.askForPlayServicesAsync();
      const { type, user } = await GoogleSignIn.signInAsync();
      if (type === 'success') {
        this._syncUserWithStateAsync();
      }
    } catch ({ message }) {
      alert('login: Error:' + message);
    }
  };

  onPress = () => {
    if (this.state.user) {
      this.signOutAsync();
    } else {
      this.signInAsync();
    }
  };

  render() {
    return <Text onPress={this.onPress}>Toggle Auth</Text>;
  }
}