For any kind of application, a login system helps to provide security & tailor made experience to the user and if you can provide an easier way to create an account and login into your system, then it’s a delightful experience for the user. In this tutorial, I’m going to show you the steps to implement Google login in a react native app and this is an extension of the previous tutorial where I’ve covered the topic to install react native firebase and add email authentication in react native using firebase.
The social login system can give your application extra acceptance to the user, it removes the barrier for a user to go through all the hassle to provide their information to register for an account and then provide login credentials to log in. Most of the people on the internet have either a Google or Facebook account, so providing these logins to your application will definitely be a great feature. So if you want to see the steps to implement Facebook login in react native using firebase you can find it here.
Here we are using react-native-CLI, react-navigation version 5, react-native-firebase version 6 and if you’re using react native 0.60+ then you’re good to go. To implement this functionality first we need to start with creating UI for those buttons in our existing project. If you want to see our project initial setup then follow the previous tutorial to setup firebase authentication in react native.
Before proceeding please note, Staring April 2020, all existing applications using external 3rd party login services (such as Facebook, Twitter, Google, etc) must ensure that Apple Sign-In is also provided. To learn more about these new guidelines, view the Apple announcement. Apple Sign-In is not required for Android devices. So we’re working on ONLY Android in this tutorial.
Creating Social Buttons
Now within components/ directory, we will create a new file called SocialButton.js and start writing the codes below.
import React from 'react'; import {Text, TouchableOpacity, View, StyleSheet} from 'react-native'; import {windowHeight, windowWidth} from '../utils/Dimentions'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; const SocialButton = ({ buttonTitle, btnType, color, backgroundColor, ...rest }) => { let bgColor = backgroundColor; return ( <TouchableOpacity style={[styles.buttonContainer, {backgroundColor: bgColor}]} {...rest}> <View style={styles.iconWrapper}> <FontAwesome name={btnType} style={styles.icon} size={22} color={color} /> </View> <View style={styles.btnTxtWrapper}> <Text style={[styles.buttonText, {color: color}]}>{buttonTitle}</Text> </View> </TouchableOpacity> ); }; export default SocialButton; const styles = StyleSheet.create({ buttonContainer: { marginTop: 10, width: '100%', height: windowHeight / 15, padding: 10, flexDirection: 'row', borderRadius: 3, }, iconWrapper: { width: 30, justifyContent: 'center', alignItems: 'center', }, icon: { fontWeight: 'bold', }, btnTxtWrapper: { flex: 1, justifyContent: 'center', alignItems: 'center', }, buttonText: { fontSize: 18, fontWeight: 'bold', fontFamily: 'Lato-Regular', }, });
Previously, we have installed the react-native-vector-icons package to our project to display icons and we are receiving props for our button component, by these props, we can customize our button while calling in on our LoginScreen.js and SignupScreen.js files, and can make multiple social buttons.
Now add these codes below to our existing LoginScreen.js file in screens/ directory.
//... import SocialButton from '../components/SocialButton'; const LoginScreen = ({navigation}) => { //... return ( <View style={styles.container}> //... <SocialButton buttonTitle="Sign In with Facebook" btnType="facebook" color="#4867aa" backgroundColor="#e6eaf4" onPress={() => {}} /> <SocialButton buttonTitle="Sign In with Google" btnType="google" color="#de4d41" backgroundColor="#f5e7ea" onPress={() => {}} /> //... </View> ); }; export default LoginScreen; //...
After this add these codes below to the existing SingupScreen.js file in screens/ directory.
//... import SocialButton from '../components/SocialButton'; const SignupScreen = ({navigation}) => { //... return ( <View style={styles.container}> //... <SocialButton buttonTitle="Sign Up with Facebook" btnType="facebook" color="#4867aa" backgroundColor="#e6eaf4" onPress={() => {}} /> <SocialButton buttonTitle="Sign Up with Google" btnType="google" color="#de4d41" backgroundColor="#f5e7ea" onPress={() => {}} /> //... </View> ); }; export default SignupScreen; //...
Adding these buttons is similar for both of these screens.
Pretty simple stuff. Right.
Now, comes the actual implementation of the Google login in react native.
Install The Package
To implement this functionality now we need to install google-signin package in our project. Run this command in your terminal
npm install @react-native-community/google-signin
After Installing it we need to do some configurations to make it work properly.
1. First, open the Firebase console and open your project, then go to Project Settings, and here you need to add the SHA-1 certificate for your android app.
For that, first, you need to generate a signing key using keytool and create keystore file for your project. Move to android/app/ directory in your terminal and run this command to create a new one on Mac.
keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 10000
For Windows, you might get keytool command not found, then keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin this path, open command prompt on that path, and then run the command mentioned above. Follow this link for more info.
After running this command debug.keystore file will be created in android/app/ directory and in your terminal, you will see SHA-1 hash.
Copy this SHA-1 hash code and paste it in the firebase console mentioned above image.
After adding it, Download a fresh google-services.json file from the firebase and place it in android/app/ directory.
2. Add few lines in the android/build.gradle file.
buildscript { ext { buildToolsVersion = "27.0.3" minSdkVersion = 16 compileSdkVersion = 27 targetSdkVersion = 26 supportLibVersion = "27.1.1" googlePlayServicesAuthVersion = "18.0.0" // <--- use this version or newer } ... dependencies { classpath 'com.android.tools.build:gradle:3.1.2' // <--- use this version or newer classpath 'com.google.gms:google-services:4.2.0' // <--- use this version or newer } ... allprojects { repositories { mavenLocal() google() // <--- make sure this is included jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } }
3. Update the android/app/build.gradle file with this line if not exist.
apply plugin: 'com.google.gms.google-services' // <--- this should be the last line
4. Go to the Authentication menu in the Firebase console within the sign-in method tab and enable Google for the sign-in provider.
Web client ID and secret will be added automatically, if not then add it from the android/app/google-services.json file as the client/oauth_client/client_id property (the id ends with .apps.googleusercontent.com).
Implement Google Login in React Native
Before triggering sign-in request, you must initialize the Google SDK using the webClientId. We need to run this code below while the app loads, so I’ve added it in the useEffect method in the AppStack.js file in the navigation/ directory.
// Other imports import { GoogleSignin } from '@react-native-community/google-signin'; const Stack = createStackNavigator(); const AuthStack = () => { useEffect(() => { // initialize the Google SDK GoogleSignin.configure({ webClientId: 'YOUR_WEB_CLIENT_ID', }); }, []); return ( //... ); }; export default AuthStack;
The webClientId can be found from the android/app/google-services.json file as you’ve just added or found in the firebase in the previous step.
Now, update the AuthProvider.js file in the navigation/ directory with the marked lines.
//Other imports import { GoogleSignin } from '@react-native-community/google-signin'; export const AuthContext = createContext(); export const AuthProvider = ({children}) => { const [user, setUser] = useState(null); return ( <AuthContext.Provider value={{ //... googleLogin: async () => { // Get the users ID token const { idToken } = await GoogleSignin.signIn(); // Create a Google credential with the token const googleCredential = auth.GoogleAuthProvider.credential(idToken); // Sign-in the user with the credential return auth().signInWithCredential(googleCredential); }, //... }}> {children} </AuthContext.Provider> ); };
Finally, call googleLogin method in the LoginScreen.js file in screens/ directory.
//... import SocialButton from '../components/SocialButton'; import { AuthContext } from '../navigation/AuthProvider'; const LoginScreen = ({navigation}) => { //... const {login, googleLogin} = useContext(AuthContext); return ( <View style={styles.container}> //... <SocialButton buttonTitle="Sign In with Google" btnType="google" color="#de4d41" backgroundColor="#f5e7ea" onPress={() => googleLogin()} /> //... </View> ); }; export default LoginScreen; //...
After adding all this, build your android app by running this command
npx react-native run-android
After clicking on Sign In with Google button the user will be prompted with a window to give permission and allow access like this.
In the Authentication menu under the Users tab of the Firebase console, we’ll see the user has been created successfully.
So, this is how we can implement google login in react native with Firebase.
Debugging
1. If you are seeing this error on Android as below
error no firebase app ‘ default ‘ has been created – call firebase.initializeapp()
Then go to android/build.gradle file and add
classpath 'com.google.gms:google-services:4.2.0' // <--- use this version or newer
Notice the version number. This fixed the problem for me.
2. If you see a DEVELOPER ERROR, then make sure you have used the correct web client ID. You can cross-check it in google developer console open your project and see the Web client in OAuth 2.0 Client IDs section, not the android client, add the credentials of it in the firebase and in your code while configuring Google SDK.
3. If you want to see your SHA-1 hash code of previously created debug.keystore file then type this command below in the terminal of android/app/ directory.
keytool -keystore debug.keystore -list -v
Also, make sure you clean the gradle build after making any changes while debugging by this command below.
cd android ./gradlew clean
After it, you can run the app again in your android emulator to test it.
Hi,
It is showing me error after i added google-services file and added the credentials in build.gradle files
I have to open and run my app through android studio and in that it doesn’t show error, but when in vs code i type “npx react-native run-android”, it shows big error
Getting below error:
A problem occurred configuring project ‘:app’.
> Failed to notify project evaluation listener.
> JAVA_LETTER_OR_DIGIT
Thank you! I appreciate your help pradip.
Hi Debnath,
Thank you for your wonderful videos on React Native. I was following your Social App and after coding Google Login, it worked in development, But after I created the apk, it is showing Google accounts to choose for login, but after I select, it is not doing anything. Can you guide me what could have gone wrong? Thanks in advance
same happend with my app
hello sir
i have an a error while i ma signing in google with fireabse the Error is
Error:Devloper error
please sir resolve my problem
i am waiting for your response
thanks
Hello sir, i have problem after following this tutorial,
so , After i released the google integrated app, i get error. which is where when i open the application and it immediately exits itself