Google SignIn with expo React Native | Solved MismatchUri | Solved Deeplinking | Solved redirect issue | React Native

Ehtishamahmedgondal
7 min readJun 23, 2024

--

Oauth in react native Expo with redirection issue

In this guide, we’ll walk you through the process of setting up a streaming app with Google authentication using Expo and Firebase. This guide assumes you are familiar with React Native development and have basic knowledge of Expo, Firebase, and Google Developer Console.

Prerequisites

Ensure you have the latest version of Expo installed.

Sign up for an Expo EAS account as it’s required for Google login functionality.

Have Node.js and npm installed on your system.

The very first thing you will need it the expo eas account beacuse with out the expo eas account google login will not work, why ? simple answer to this question is deeplinking issue in during developemnt, Redirect uri does not work which mean that you will not be redirected back to app after successfull authenticaion even the most worst thing is you will be given propmt of mismatch uri authentication blocked when you will go for the google sigin , I litterly send whole week just to make sure what I am doing worng , don’t worry you will be given with each step to make sure you don’t face the same problme , just dont miss any step

Step 1 project creation at the Expo eas

Go to Link

Expo dev

Create account there then in the project seciton create new project add the project name , slug can be any name/slug but this will be used later Then you will be given some commands to run.

npm install --global eas-cli
npx create-expo-app random
cd random
eas init --id ******************

If you have any issue in expo installation then just go for any video of on youtube for expo setup. Simply run the commands in sequence on terminal last command should be inside your project , you will get the meassage of successfull linkage of you project

Step 2 Package installation

First you will need to install following packages in your project I am mentioning Version first so you make sure you work with same versions

"@expo/metro-runtime": "^3.1.3",
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-native-firebase/app": "^19.1.1",
"@react-native-firebase/auth": "^19.1.1",
"@types/react": "~18.2.45",
"expo": "~50.0.14",
"expo-auth-session": "~5.4.0",
"expo-crypto": "~12.8.1",
"expo-status-bar": "~1.11.1",
"expo-system-ui": "~2.9.3",
"expo-web-browser": "~12.8.2",
"firebase": "^10.10.0",
"jwt-decode": "^4.0.0",
"react": "18.2.0",
"react-dom": "^18.2.0",
"react-native": "0.73.6",
"react-native-web": "^0.19.10",
"typescript": "^5.3.0"

Run following command

npx expo install @expo/metro-runtime @react-native-async-storage/async-storage @react-native-firebase/app @react-native-firebase/auth @types/react expo expo-auth-session expo-crypto expo-system-ui expo-web-browser firebase react react-dom react-native react-native-web typescript

OR

npm install @expo/metro-runtime @react-native-async-storage/async-storage @react-native-firebase/app @react-native-firebase/auth @types/react expo expo-auth-session expo-crypto expo-system-ui expo-web-browser firebase react react-dom react-native react-native-web typescript

Step 4 PreBuild & Building app

Now run this command to create ios and android folder or any one of them .

npx expo prebuild

This will create the android/ios folder in main app. Before moving to next step you need to make the file in android folder root .

Name the file as local.properties

Now add the skd and ndk path to this file Should be like this save file

You can get these path form your Program files make sure to add \ arrow before each directory otherwise it will not pickup path.

sdk.dir = C:\\Users\\Hp\\AppData\\Local\\Android\\Sdk 
ndk.dir=C:\\Users\\Hp\\AppData\\Local\\Android\\Sdk\\ndk\\26.2.11394342

One thing more to confirm that you have javasdk 17 version installed in your system . If not please download from official site Java Versions.

After installing adds its path to your enviornment variable file and you are done

Now you can easily build your app with the command of

expo run:android expo run:ios

This will build app and run on your device either physcial or emulator

Now you need to run this to make you app SHA1 Fingerprint credetails For that first make sure you have login your eas account in terminal by running eas login

eas login

Add the email and password of you eas account Now run

eas credentials

It will ask you to select for andriod/ios select any depending upon need and select keystroke -> create new keystorke -> and then hit enter -> enter and you will be given keys form there copy the SHA1 key becuase you will need it later

Step 5: Google console setup

To create credentials in the Google Developer Console for various client types (web, iOS, Android, Expo), follow these steps:

Web Client ID:

  1. Navigate to the Google Developer Console and select your project.
  2. Go to “API & Services” > “OAuth consent screen”.
  3. Select “External” and click “Create”.
  4. Fill in the required fields such as the project name, contact email, and developer email. Skip other optional fields.
  5. Save and continue through the screens until the process is complete.
  6. Go back to the dashboard.
  7. Now, navigate to “API & Services” > “Credentials”.
  8. Click on “Create credentials” and select “OAuth client ID”.
  9. Choose “Web application” as the application type.
  10. Add the project name, package name (from your app.json file), and set the redirect URIs and Authorization Origin URI to “http://localhost:19006".
  11. Save the Client ID generated.

iOS Client ID:

  1. Follow steps 7–9 above to reach the credentials page.
  2. Choose “iOS application” as the application type.
  3. Add the project name and bundle ID (from your app.json file).
  4. Save the Client ID generated.

Android Client ID:

  1. Follow steps 7–9 above to reach the credentials page.
  2. Choose “Android application” as the application type.
  3. Add the project name and package name (from your app.json file).
  4. Enter the SHA1 key obtained from the credentials generated using eas credentials.
  5. Ensure that “CUSTOM URI” option is marked as true.
  6. Save the Client ID generated.

Expo Client ID:

  1. Follow steps 7–9 above to reach the credentials page.
  2. Choose “iOS application” as the application type.
  3. Add the project name.
  4. Add the redirect URIs.
  5. Save the Client ID generated.

Make sure to document each Client ID properly for future reference and integration into your project.

https://auth.expo.io/user_name_on_expo/app_name_on_expo

Add the Authorization Origin uri :

https://auth.expo.io

save the ClientId some where

Jjust save miss other feilds

Step 6 : FireBase setup

Now go to the firebse console

https://console.firebase.google.com

Create a new project there

steps to create project

select plus icon there add the name of project and select the account to use if not then create just easy step,

Open that project on top left corner click add App

select the web option add the name of project (this should be the pkg name as in app.json file)

Then you will be given npm command to install miss it as we have already installed all pkges

Come back to your project run this command

npx expo customize metro.config.js

A file will be created with name of metro.config.js open it and add this code there remove previous one

const { getDefaultConfig } = require('@expo/metro-config');  const defaultConfig = getDefaultConfig(__dirname); defaultConfig.resolver.sourceExts.push('cjs');  module.exports = defaultConfig;

Create the file firebaseConfig.js in root of you project

Now go back to firebase console

Now you will be given code of firebase config copy it and paste it in file of firebaseConfig.js

Now open the project go to authentication part and select auth methods First login with email and passowrd Second Continue with google and enable it and save it

Step 7 Code part

First make sure your firebaseConfig.js look like this

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { initializeAuth, getReactNativePersistence} from 'firebase/auth'
import { ReactNativeAsyncStorage } from '@react-native-async-storage/async-storage';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "**********",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
persistence: getReactNativePersistence(ReactNativeAsyncStorage)
});

export {auth};
// const analytics = getAnalytics(app);

Your App.js should be like this

import { StatusBar } from 'expo-status-bar';
import { Button, StyleSheet, Text, TextInput, ToastAndroid, View } from 'react-native';
import * as AuthSession from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Google from 'expo-auth-session/providers/google'
import React, { useState } from 'react';
import jwtDecode from 'jwt-decode';
import { signInWithCredential, GoogleAuthProvider, onAuthStateChanged } from "firebase/auth";
import {auth} from './firebaseConfig';
import * as Linking from 'expo-linking';
 
Add the following code there
WebBrowser.maybeCompleteAuthSession();
export default function App() {
const [userInfo, setUserInfo] = React.useState();

``` const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: "", //add the ids that we created form google developer console
androidClientId: "",
webClientId: "",
iosClientId: "",
});
````
React.useEffect(() => {
if (response?.type == 'success') {
const { id_token } = response.params;
const credentials = GoogleAuthProvider.credential(id_token);
ToastAndroid.show("SuccessFull Login ", ToastAndroid.SHORT)
signInWithCredential(auth, credentials)
}
}, [response])

React.useEffect(() => {
//in order to check the state of logged in user
const unsub = onAuthStateChanged(auth, async (user) => {
if (user) {
setUserInfo(user);
console.log("user info : ", user.displayName, user.email);
await AsyncStorage.setItem("@user", JSON.stringify(user));
ToastAndroid.show("Logged in! ", ToastAndroid.SHORT)
} else {
ToastAndroid.show("Logged out! ", ToastAndroid.SHORT)
}
})
return () => unsub;
}, [])
return (
<View style={styles.container}>
<Text>This is my App!</Text>
<Text></Text>
<Text></Text>
<Text></Text>
<Button title='Google LogIn' onPress={handleLogin} ></Button>
<TextInput placeholder='Enter value'></TextInput>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

You are all set ,

IF you find any import missing jsut run ``npm install `` or manually downlaod it

Last Step to make sure you don’t get and error for Unmatched route when it redirect back to your app

Add this code in your page where you are handling singinwithgoogle

React.useEffect(() => {
const handleRedirect = (event) => {
const { url } = event;
const params = url.split('?')[1];
const queryParams = new URLSearchParams(params);
      const code = queryParams.get('code');
if (code) {
router.replace('home');
} else {

}
}
Linking.addEventListener('url', handleRedirect);
}, [response]);

--

--

Ehtishamahmedgondal
0 Followers

Hi there! I'm a skilled software engineer with expertise in full-stack development, specializing in MERN, React Native, SQL, MySQL, Flutter, Dart, and C/C++.