Google AUTH in React Native Expo

Simplify Authentication with Appwrite in React Native: A Step-by-Step Guide

Introduction
Authentication is a crucial component of modern applications, ensuring user data security while delivering a personalized experience. This guide simplifies the authentication process using Appwrite, an open-source backend server, in a React Native project. Follow these steps to get started!


Step 1: Open Appwrite

  1. Open your preferred browser and navigate to Appwrite.
  2. Sign up or log in to your account.

Step 2: Create a New Project

  1. In the Appwrite dashboard, create a new project.
  2. After creating the project, copy the Project ID — you’ll need it to initialize the Appwrite client in your code.

Step 3: Setting Up Authentication

Below is the React Native code to implement authentication using Appwrite.

Code for Authentication

javascript
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import { Client, Account, OAuthProvider } from 'appwrite';

// Initialize Appwrite client
const client = new Client()
.setEndpoint('https://cloud.appwrite.io/v1') // Replace with your Appwrite endpoint
.setProject('replace with your project id'); // Replace with your Appwrite project ID

const account = new Account(client);

interface User {
name?: string;
email?: string;
[key: string]: any;
}

const App = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [user, setUser] = useState<User | null>(null);

useEffect(() => {
// Check if the user is already logged in when the app is loaded
account.get()
.then(response => {
setIsLoggedIn(true);
setUser(response);
})
.catch(() => {
setIsLoggedIn(false);
setUser(null);
});
}, []);

// Login with Google
const loginWithGoogle = () => {
const successUrl = 'http://localhost:8081/success';
const failureUrl = 'http://localhost:8081/fail'; // Replace with actual URLs

account.createOAuth2Session('google' as OAuthProvider, successUrl, failureUrl)
.then(() => {
account.get()
.then(response => {
setIsLoggedIn(true);
setUser(response);
Alert.alert('Login Successful', `Welcome, ${response.name}`);
})
.catch(error => {
console.error('Fetching user data failed:', error);
Alert.alert('User Data Error', error.message);
});
})
.catch(error => {
console.error('Login failed:', error);
Alert.alert('Login Error', error.message);
});
};

// Logout
const logout = () => {
account.deleteSession('current')
.then(() => {
setIsLoggedIn(false);
setUser(null);
Alert.alert('Logged Out', 'You have been successfully logged out.');
})
.catch(error => {
console.error('Logout failed:', error);
Alert.alert('Logout Error', error.message);
});
};

return (
<View style={styles.container}>
{isLoggedIn ? (
<>
<Text style={styles.welcomeText}>Welcome, {user?.name || 'User'}!</Text>
<Button title="Logout" onPress={logout} />
</>

) : (
<Button title="Login with Google" onPress={loginWithGoogle} color="#4285F4" />
)}
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5f5f5',
},
welcomeText: {
fontSize: 18,
marginBottom: 20,
},
});

export default App;


Step 4: Understanding the Code

  1. Appwrite Client Initialization:
    • Replace replace with your project id with your actual Project ID from the Appwrite dashboard.
    • Replace the endpoint URL with your Appwrite instance URL (https://cloud.appwrite.io/v1 for Appwrite Cloud).
  2. Login Functionality:
    • loginWithGoogle() uses Appwrite’s OAuth 2.0 integration to authenticate users via Google.
    • Upon successful login, it fetches and displays user details.
  3. Logout Functionality:
    • logout() terminates the current session, logging the user out.
  4. UI Elements:
    • A simple interface to toggle between login and logout states.

Conclusion

With this guide, you’ve implemented a seamless authentication process in a React Native app using Appwrite. You can expand this functionality to include additional OAuth providers, user role management, and data security to suit your application’s needs.

Happy coding! 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *