akshay-khapare-react-native-firebase-google-signin
v1.0.3
Published
A production-ready React Native package for your app
Maintainers
Readme
React Native Firebase Google Sign-In
A production-ready React Native package to seamlessly integrate Google Sign-In with Firebase Authentication. This package provides a simple, promise-based API to handle the entire authentication flow, complete with robust error handling and TypeScript support.
Features
- ✅ Simple API: A minimal set of functions (
init,googleSignIn,signOut) to manage the auth lifecycle. - 🔥 Firebase Integration: Directly returns Firebase user credentials (
FirebaseAuthTypes.UserCredential) on successful sign-in. - 🚨 Robust Error Handling: Provides a custom
AppErrorclass with specific error codes (GoogleSignInErrorCode) for predictable error management. - ⚙️ Pre-flight Checks: Automatically verifies Google Play Services availability on Android before initiating sign-in.
- 🔒 Typed with TypeScript: Fully typed for a better developer experience and safer code.
Installation
Install the package and its peer dependencies using your preferred package manager:
npm install akshay-khapare-react-native-firebase-google-signinPeer Dependencies
This package relies on other libraries to function. You must install them in your project:
# Using npm
npm install @react-native-firebase/app @react-native-firebase/auth @react-native-google-signin/google-signin react react-native
# Using yarn
yarn add @react-native-firebase/app @react-native-firebase/auth @react-native-google-signin/google-signin react react-nativeSetup & Configuration
Before using this package, you need to configure both Firebase and Google Sign-In for your React Native application.
1. Firebase Setup
- Ensure you have a Firebase project and have registered your iOS and/or Android app.
- Add the
@react-native-firebase/appand@react-native-firebase/authpackages to your project. - For Android, place the
google-services.jsonfile in theandroid/appdirectory. - For iOS, add the
GoogleService-Info.plistfile to your Xcode project.
For a detailed guide, follow the official React Native Firebase installation instructions: https://rnfirebase.io/
2. Google Sign-In Setup
- Follow the setup guide for
@react-native-google-signin/google-signin. - The most crucial step is to obtain the Web client ID from your Google Cloud Console credentials. This is required to initialize the library.
For a detailed guide, follow the official React Native Google Sign-In installation instructions: https://github.com/react-native-google-signin/google-signin#setup
Usage
1. Initialize the Package
Call the init function once during your app's startup, such as in your main App.tsx file. Provide the Web Client ID you obtained during setup.
// App.tsx
import { init } from 'akshay-khapare-react-native-firebase-google-signin';
// Your Web Client ID from Google Cloud Console
const WEB_CLIENT_ID = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com';
init({
webClientId: WEB_CLIENT_ID,
});2. Implement Sign-In and Sign-Out
Use the googleSignIn and signOut functions to manage the user's session.
import React, { useState } from 'react';
import { View, Button, Text, Alert } from 'react-native';
import { FirebaseAuthTypes } from '@react-native-firebase/auth';
import {
googleSignIn,
signOut,
AppError,
GoogleSignInErrorCode,
} from 'akshay-khapare-react-native-firebase-google-signin';
const AuthScreen = () => {
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
const [loading, setLoading] = useState(false);
const handleSignIn = async () => {
setLoading(true);
try {
const { user } = await googleSignIn();
setUser(user);
Alert.alert('Success', `Signed in as ${user.displayName}`);
} catch (error) {
if (error instanceof AppError) {
// Handle specific, known errors
if (error.code === GoogleSignInErrorCode.SIGN_IN_CANCELLED) {
Alert.alert('Cancelled', 'You cancelled the sign-in process.');
} else {
Alert.alert('Sign-In Error', error.message);
}
} else {
// Handle unexpected errors
Alert.alert('An Unknown Error Occurred', (error as Error).message);
}
} finally {
setLoading(false);
}
};
const handleSignOut = async () => {
try {
await signOut();
setUser(null);
Alert.alert('Success', 'You have been signed out.');
} catch (error) {
Alert.alert('Sign-Out Error', (error as Error).message);
}
};
return (
<View>
{user ? (
<View>
<Text>Welcome, {user.displayName}</Text>
<Button title="Sign Out" onPress={handleSignOut} />
</View>
) : (
<Button
title="Sign in with Google"
onPress={handleSignIn}
disabled={loading}
/>
)}
</View>
);
};
export default AuthScreen;API Reference
init(config: GoogleSignInConfig)
Configures the Google Sign-In library. Must be called once before any other functions.
config: An object with the following properties:webClientId: string: (Required) The Web Client ID from your Google Cloud project credentials.offlineAccess?: boolean: (Optional) If you want to access Google APIs on behalf of the user while they are offline. Defaults totrue.
async googleSignIn(): Promise<FirebaseAuthTypes.UserCredential>
Initiates the Google Sign-In flow and authenticates with Firebase.
- Returns: A
Promisethat resolves with the FirebaseUserCredentialobject upon success. - Throws: An
AppErrorif the sign-in fails for a known reason (e.g., cancelled by user, Play Services unavailable) or a standardErrorfor other issues.
async signOut(): Promise<void>
Signs the user out from both Google and Firebase.
- Returns: A
Promisethat resolves when the sign-out is complete. - Throws: An
AppErrorif the sign-out fails.
Error Handling
The package exports helpers to make error handling predictable.
AppError
A custom error class that extends Error. It includes a code property to identify the type of error.
message: string- A user-friendly error message.code?: string- A machine-readable code fromGoogleSignInErrorCode.
GoogleSignInErrorCode
An enum containing specific error codes you can check against:
| Code | Description |
| ------------------------------- | ----------------------------------------------------------- |
| NO_ID_TOKEN | The Google Sign-In response did not include an idToken. |
| USER_CREDENTIAL_INVALID | The Firebase user credential was invalid. |
| PLAY_SERVICES_NOT_AVAILABLE | Google Play Services are missing or outdated on Android. |
| SIGN_IN_CANCELLED | The user cancelled the native Google Sign-In prompt. |
| SIGN_IN_FAILED | A generic or unknown sign-in error occurred. |
Contributing
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
License
This project is licensed under the MIT License. See the LICENSE file for details.
