Search
  • Kyle

React Native Google Login


photo by Arthur Osipyan from Unsplash


Social media Authentication like Google login is becoming necessary while building the authentication flow of a mobile app. In React Native, this can easily be achieved in a few minutes.


Requirements

  • expo-google-app-auth

Go ahead and install expo-google-app-auth dependency with:

expo install expo-google-app-auth

The only method you need

import * as Google from "expo-google-app-auth";

const config = {
 androidClientId: YOUR_CLIENT_ID_HERE,
 iosClientId: YOUR_CLIENT_ID_HERE,
 scopes: ['profile', 'email'],
};

const logInWithGoogle = async () => {
 try {
   const { type, accessToken, user } = await Google.logInAsync(config);
   if (type === "success") {
     /* `accessToken` is now valid and can be used to get data from the Google API with HTTP requests like below */
     let response = await fetch(
      'https://www.googleapis.com/userinfo/v2/me',
      {
       headers: { Authorization: `Bearer ${accessToken}` },
      },
      );
     response && console.log(response);
   } else {
    // type === 'cancel'
   }
 } catch ({ message }) {
    alert(`Google Login Error: ${message}`);
 }
};

(If you need an already implemented solution, get free and premium templates with the complete backend at QuickComponent).


To log the user out use method:

Google.logOutAsync({ accessToken }) - pass the accessToken previously gotten during login to invalidate it.


follow the detailed instructions here to see how to get values of Google Login config such as; iosClientId and androidClientId.


For more information on other methods, you might need, visit expo-google-app-auth official documentation here

This post was inspired by the post on react native google login.



#reactnative #google #login #mobileapp

2 views0 comments