React Native Firebase Phone Authentication With Typescript

Pritam Banerjee
Webtips
Published in
6 min readDec 7, 2020
React Native Firebase Phone Authentication For Expo Project

Introduction

React Native and Firebase are one of the best choices to create mobile applications. Firebase provides a lot of services under the hood like Authentication, Cloud Firestore Database, Analytics, ML, Hosting, Cloud Functions, and many more which will give most of the features that are necessary to create large scale by default real time mobile application.

So for any mobile application phone number authentication is played an important role and nowadays people are often using phone authentication instead of email authentication because it is easier to track and no password is required to remember, So it is easier to manage authentication for end-user and as well as for developers. So firebase Auth provides various kinds of ways for Authentication like, Email Authentication, Google Authentication, Phone Authentication etc. So in this tutorial, I will explain to you how to create React Native Authentication for expo based React Native Apps.

Installation

In your Expo React Native Project, you need to install a minimum of two libraries and that are firebase and expo-firebase-Recaptcha using npm and expo.

$ npm install firebase, expo-firebase-recaptcha
$ expo install firebase, expo-firebase-recaptcha

Add Firebase Configuration

In this project we need to add firebase configuration, So you need to go to firebase and create a firebase project and then copy the firebase web configuration and then initialize the firebase configuration using firebase.initializeApp(firebaseConfig) function which will look like this given below.

firebase.config.ts

import * as firebase from 'firebase';import '@firebase/auth';import '@firebase/firestore';export const firebaseConfig: any = {apiKey: "***********************",authDomain: "***********************",databaseURL: "***********************",projectId: "***********************",storageBucket: "***********************",messagingSenderId: "***********************",appId: "***********************",measurementId: "***********************"};if (!firebase.apps.length) {firebase.initializeApp(firebaseConfig);}

So you have seen that if the apps exist then we initialize our firebase project and now it is connected with firebase, so let's use this to create a phone authentication system using React Native.

Create Auth.tsx File for Authentication

We will create Auth.tsx functional components where we will do the Firebase Phone Number Authentication, we will use React Hooks and React Context API. So first import required components which are required to design the page and implement the phone number Authentication. FirebaseRecaptchaVerifierModal and FirebaseRecaptchaBanner are the two main components from expo-firebase-recaptcha module which are required to implement the firebase phone number authentication. After that, we will import the firebase module and firebaseConfig.

import * as React from 'react';import {Text,View,TextInput,Button,StyleSheet,TouchableOpacity,Platform,} from 'react-native';import { FirebaseRecaptchaVerifierModal, FirebaseRecaptchaBanner } from 'expo-firebase-recaptcha';import * as firebase from 'firebase';import { firebaseConfig } from '../../firebase.config';export default function Auth() {<View style={{ padding: 20, marginTop: 50 }}>
<Text>Authentication</Text></View>
);
}

So after creating a simple Auth Functional component let's write the required Phone Number Authentication Code with react hooks.

Full Phone Number Authentication Code:

import * as React from 'react';import {Text,View,TextInput,Button,StyleSheet,TouchableOpacity,Platform,} from 'react-native';import { FirebaseRecaptchaVerifierModal, FirebaseRecaptchaBanner } from 'expo-firebase-recaptcha';import * as firebase from 'firebase';import { firebaseConfig } from '../../firebase.config';// Initialize Firebase JS SDK// https://firebase.google.com/docs/web/setup/*try {firebase.initializeApp({...});} catch (err) {// ignore app already initialized error in snack}*/export default function Auth({ navigation }: any) {const recaptchaVerifier: any = React.useRef(null);const [phoneNumber, setPhoneNumber]: any = React.useState();const [verificationId, setVerificationId]: any = React.useState();const [verificationCode, setVerificationCode]: any = React.useState();const [message, showMessage]: any = React.useState(!firebaseConfig || Platform.OS === 'web'? {text:'To get started, provide a valid firebase config in App.js and open this snack on an iOS or Android device.',}: undefined);const attemptInvisibleVerification = false;return (<View style={{ padding: 20, marginTop: 50 }}><FirebaseRecaptchaVerifierModalref={recaptchaVerifier}firebaseConfig={firebaseConfig}attemptInvisibleVerification={attemptInvisibleVerification}/><Text style={{ marginTop: 20 }}>Enter phone number</Text><TextInputstyle={{ marginVertical: 10, fontSize: 17 }}placeholder="+1 999 999 9999"autoFocusautoCompleteType="tel"keyboardType="phone-pad"textContentType="telephoneNumber"onChangeText={phoneNumber => setPhoneNumber(phoneNumber)}/><Buttontitle="Send Verification Code"disabled={!phoneNumber}onPress={async () => {// The FirebaseRecaptchaVerifierModal ref implements the// FirebaseAuthApplicationVerifier interface and can be// passed directly to `verifyPhoneNumber`.try {const phoneProvider = new firebase.auth.PhoneAuthProvider();const verificationId = await phoneProvider.verifyPhoneNumber(phoneNumber,recaptchaVerifier.current);setVerificationId(verificationId);showMessage({text: 'Verification code has been sent to your phone.',});setTimeout(() => showMessage({text: undefined,}), 5000);} catch (err) {showMessage({ text: `Error: ${err.message}`, color: 'red' });}}}/><Text style={{ marginTop: 20 }}>Enter Verification code</Text><TextInputstyle={{ marginVertical: 10, fontSize: 17 }}editable={!!verificationId}placeholder="123456"onChangeText={setVerificationCode}/><Buttontitle="Confirm Verification Code"disabled={!verificationId}onPress={async () => {try {const credential = firebase.auth.PhoneAuthProvider.credential(verificationId,verificationCode);await firebase.auth().signInWithCredential(credential);showMessage({ text: 'Phone authentication successful 👍' });setTimeout(() => {showMessage({text: undefined,});navigation.navigate('Register'), 3000});} catch (err) {showMessage({ text: `Error: ${err.message}`, color: 'red' });}}}/><View style={styles.messageStyle}>{message ? (<TouchableOpacitystyle={[StyleSheet.absoluteFill,{ backgroundColor: '0xffffffee', justifyContent: 'center' },]}onPress={() => showMessage(undefined)}><Textstyle={{color: message.color || 'green',fontSize: 17,textAlign: 'center',margin: 20,}}>{message.text}</Text></TouchableOpacity>) : (undefined)}</View>{attemptInvisibleVerification && <FirebaseRecaptchaBanner />}</View>);}const styles = StyleSheet.create({messageStyle: {marginTop: 30,paddingTop: 30}});

So we have created some react hooks like ‘recaptchaVerifier’ which is used to verify to captcha, then we have used phoneNumber hooks which is required to verify the Phone Number and set Phone Number in input box. verificationId hook will use to set Phone Number and Current Recaptcha details, So once it is set then we will pass it on button on pressed firebase phoneAuthProvider credential function where it will validate and do the phone number authentication.

In the JSX you can see that we have given ‘FirebaseRecaptchaVerifierModal’ component and it will take three props one is ref where we need to define the ‘recaptchaVerifier’ second it will take firebaseConfig where you need to provide your firebaseConfig variable, So it will understand that for which project we need to do the Phone Number Authentication and also make sure that you will the Phone Number Authentication from Firebase console. Last it will take attemptInvisibleVerification props where we pass a variable name ‘attemptInvisibleVerification’ and it will take a boolean value and the initial value should be always false.

Verification Code and Submit Handler:

After that we you will give a phone number with the proper country code then it will send you an OTP and that OTP you need to put in OTP input field and it will validate it and if it is successfully validated then it will redirect to the next page for our case we have redirected to profile page, so if in your project if react-navigation is enabled then you can do the route. firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);

which will do the code validation, So once your OTP or Code is correct then you will successfully be logged in and you can see that if you are a new user then the user will be added in the Authentication field in Firebase. I have added one user using phone number authentication in firebase and the screenshot is given below.

Conclusion:

So if you are building a mobile application using React Native with expo then this will be the right and easy way to create Phone Number Authentication using Firebase. We have just shown you a basic flow that how to to create a phone number authentication but you can customize it in your own way for more advanced features. But this phone number authentication really simplifies the phone authentication solution without relying on third parties gateway and it is very secure, easy to use, and can be used for any geo-location. So follow this tutorial and create your own Phone Authentication system using Firebase and React Native.

--

--

Pritam Banerjee
Webtips

I am Full Stack Developer and Data Scientist, I have worked some of the biggest client’s project (eg. Walmart, Cisco, Uber, Apple, JP Morgan, Capital One etc).