React Native Google Sign-In Complete Tutorial

Learn via video courses
Topics Covered

Overview

In the world of React Native development, integrating social sign-in functionality is a common requirement for many applications. One popular option is Google Sign-In, which allows users to authenticate with their Google accounts and access various Google services seamlessly. However, implementing this functionality can be complex and time-consuming. That's where the React native Google sign-in library comes to the rescue. In this article, we will explore the features and benefits of this powerful library and learn how it simplifies the process of integrating Google Sign-In into React Native applications.

React-native-google-signin

React-native-google-signin is a library that provides functionality for integrating Google Sign-In into React Native applications. It allows users to authenticate with their Google accounts and access various Google services and APIs within the app. The package provides methods and components that streamline the process of implementing Google Sign-In, handling user authentication, and retrieving user information from Google. It is commonly used in React Native projects that require Google authentication and integration with Google services.

Prerequisites

You need to have RN >= 0.60 to use React native Google sign for your project.

Features

The application is designed to accommodate all three types of authentication methods. These methods include standard authentication, which is the conventional approach. It also supports authentication with server-side validation, where the server verifies the authenticity of the user. Additionally, it facilitates authentication with offline access, also known as server-side access, allowing users to authenticate even when they are not connected to the server.

  • Promise-based API:
    The application provides a promise-based API that ensures consistency across both the Android and iOS platforms. This means that developers can rely on a unified programming interface when implementing authentication features, regardless of the operating system.

  • Typings for TypeScript and Flow:
    To enhance the development experience, the application includes typings for TypeScript and Flow. These typings serve as type definitions that enable static type checking during development. Developers using TypeScript or Flow can benefit from improved code quality and catch potential type-related errors early on.

  • Mock of the native module for testing with Jest:
    For effective testing, the application offers a mock of the native module specifically designed for use with Jest. This mock module allows developers to simulate the behavior of the native module during testing, ensuring that authentication functionalities can be thoroughly tested in a controlled environment.

  • Native sign-in buttons:
    The application provides native sign-in buttons, which are designed to seamlessly integrate with the platform's user interface. These buttons allow users to sign in to the application using their preferred authentication method, providing a familiar and intuitive experience consistent with the platform's design guidelines.

Setup and Initialization

Installations

Install the React native Google sign-in API using the below commands. For npm users:

For yarn users:

Once you have successfully installed this npm package, you can incorporate the config plugin into the plugin array of either your app.json or app.config.js file.

APIs

The React Native Google sign-in provides the following APIs:-

GoogleSignin:

configure(options): void

Before invoking the signIn() and signInSilently() functions, it is essential to execute this method. This particular method operates synchronously, enabling immediate subsequent calls to signIn() or signInSilently().

Generally, the configure function should be invoked once after your application initiates.

In the native layer, this function is executed synchronously, and it offers optional parameters. A sample utilization with default settings involves retrieving the user's email address and basic profile information.

signIn(options: { loginHint?: string })

The user is presented with a modal that enables them to authenticate themselves within your application. Upon successful completion, a resolved promise provides an userInfo object, while any errors encountered result in a rejection.

Within the options, there exists a single key named "loginHint," which pertains exclusively to iOS and allows prefilling the authentication UI with the user's ID or email address, if feasible.

addScopes(options: { scopes: Array })

Creating Required Keys

The userInfo object is returned by this approach, or null is returned when there is no logged-in user. It is possible to omit this particular call by providing the necessary scopes during the configure call. Nonetheless, if there is a desire to acquire additional scopes at a later stage, employing this call becomes useful.

Example:

signInSilently()

You may choose to name it, for example, once your primary element is mounted. This function provides a Promise that will be fulfilled with the current user or rejected with an error if applicable.

For guidance on error handling, refer to the signIn() function.

isSignedIn()

The provided technique allows for determining whether a user has previously logged in. It provides a promise that resolves to a boolean value, ensuring that it will not reject. In the underlying system, this function operates synchronously and resolves even when the device lacks an internet connection.

It is important to note that although isSignedIn() can return true, getCurrentUser() may return null. In such cases, invoking signInSilently() can be used to retrieve the user's information. Nevertheless, it is possible for signInSilently() to reject with an error, such as when a network problem occurs.

getCurrentUser()

The outcome of this approach is either a null value or a userInfo object that pertains to the user who is currently logged in. The function never declines, and in the underlying code, it is executed synchronously.

clearCachedAccessToken(accessTokenString)

The impact of this technique is limited to Android devices. In the case of an invalid token, encountering a 401 Unauthorized error is possible. To resolve this, utilize this particular approach to eliminate the token from the local cache, followed by invoking the getTokens() function to obtain updated tokens.

When applied to iOS, this method has no effect and consistently resolves the issue. This discrepancy arises from the fact that on iOS, the getTokens() function always returns valid tokens, refreshing them beforehand if they are close to expiration or have already expired.

signOut()

It is used for signing out the currently logged in user. Code example:

revokeAccess()

To eliminate your application from the list of authorized applications for the user.

hasPlayServices(options)

Verifying the presence of Google Play Services on the device is essential to display the sign-in interface, but it does not hold significance for executing configuration and silent sign-in calls on iOS.

As a result, we suggest directly invoking the hasPlayServices function before initiating the sign-in process.

The function hasPlayServices takes in an argument, represented as an object that includes a sole key: showPlayServicesUpdateDialog (with a default value of true).

In the case where showPlayServicesUpdateDialog is set to true, the library will display a dialog box to the user, requesting their action to resolve the matter, as depicted in the accompanying illustration.

Implementing Google Sign-In in React Native

When analyzing the sign-in process, these tools prove beneficial in identifying the specific type of error that has taken place. It is recommended to import the statusCodes module in conjunction with GoogleSignIn.

These predefined values are extracted from the native error codes of GoogleSignIn and are tailored to each platform's requirements. To implement the react native Google sign-in in your project it is advisable to compare the error.code with statusCodes.SIGN_IN_CANCELLED or statusCodes.IN_PROGRESS, rather than solely relying on the raw value of error.code, for accurate error detection.

NameDescription
SIGN_IN_CANCELLEDThis code is triggered when the user cancels the sign-in process intentionally, terminating the flow.
IN_PROGRESSThis code indicates that another operation, such as invoking signInSilently, is being attempted while a previous operation is still in progress. If signInSilently is called multiple times, the native module will execute multiple signInSilently calls. The promise from the initial call to signInSilently will be rejected with this error, while the subsequent calls will resolve or reject based on the outcome of the native module.
SIGN_IN_REQUIREDThis code is particularly useful when used in conjunction with signInSilently(). It signifies that no user has signed in yet, and a sign-in process is required to proceed.
PLAY_SERVICES_NOT_AVAILABLEThis code is specific to Android and is triggered when Google Play services are either not available or outdated on the device. This situation can only occur on Android platforms.

GoogleSigninButton

This is used to add the Sign in the Google button.

Props:

The following table presents the available options for each parameter:

ParameterPossible Values
sizeSize.Icon, Size.Standard, Size.Wide (default: Size.Standard)
colorColor.Dark, Color.Light
disabledBoolean (true/false)
onPressFunction

Please note that for the "size" parameter, the recommended sizes are as follows:

  • Size.Icon: 48 x 48
  • Size.Standard: 230 x 48
  • Size.Wide: 312 x 48

By default, the recommended size based on the "size" prop will be applied. However, you have the option to override it by passing the "style" prop as in style={{ width, height }}.

For the "color" parameter, you can choose between Color.Dark, which applies a blue background, and Color.Light, which applies a light gray background.

The "disabled" parameter is a boolean value. If set to true, all interactions for the button will be disabled.

Lastly, the "onPress" parameter refers to the handler that will be called when the user taps the button.

userInfo

Upon successful sign-in, a set of user information is provided as output.

Error Possibilities

Here are solutions to address some commonly encountered challenges:

  1. An android issue that may arise is the occurrence of the "DEVELOPER_ERROR" when the SHA1 key is not correctly implemented. While various methods can be found online to generate the key, the approach mentioned in this article proved effective, unlike others that were attempted without success.

  2. In case you encounter a null value for the idToken, there is a workaround available. To obtain the idToken, it is necessary to create a new OAuth client ID credential specifically for the web application. Additionally, in the section of the code where iOS and Android keys are added using "GoogleSignin.configure({...," it is important to include these two new keys as well.

    Once you initiate this process, the userInfo object will begin including the idToken upon the user's login.

  3. In case you encounter the Exception 'Your app lacks support for the following URL schemes,' include the following import statement in the AppDelegate.m file:

    Ensure the successful building of the project in XCode before proceeding to execute the project from VSCode. It is imperative to verify the accurate implementation of the iOS URL scheme mentioned earlier.

FAQs

Q: How can I handle authentication events and retrieve user information?

A: The library offers convenient methods to handle authentication events, such as successful sign-in or sign-out. You can implement event listeners to respond to these events accordingly. Moreover, react-native-google-signin / google-signin provides methods to retrieve user information, including the user's name, email, profile picture, and other relevant data.

Q: How do I set up the necessary credentials for React native Google sign-in?

A: To use react-native-google-signin / google-signin, you need to set up credentials on the Google Developer Console. This involves creating a project, enabling the Google Sign-In API, and obtaining the necessary OAuth client credentials. Detailed instructions on setting up credentials can be found in the library's documentation.

Q: Can I customize the Google Sign-In button appearance?

A: Yes, you can customize the appearance of the Google Sign-In button using the provided styling options in the library. You can modify the button's color, text, size, and other properties to match your app's design.

Conclusion

In conclusion,

  • react-native-google-signin / google-signin is a powerful library for integrating Google Sign-In into React Native apps.
  • It offers seamless authentication using Google accounts and access to various Google services.
  • Detailed documentation and code examples make it easy to set up and initialize the library.
  • Prerequisites and installation steps help developers create keys and implement Google Sign-In.
  • The library includes robust error handling for a smooth user experience.
  • It simplifies the process of incorporating Google Sign-In into React Native apps, saving developers time and effort.