How to Add Google Login to Your React App

A complete guide to implementing secure Google Sign-In with Firebase Authentication in React applications

Introduction

Implementing Google Sign-In in a React application provides users with a familiar, secure authentication method without the hassle of managing passwords. This comprehensive guide walks you through the entire process--from setting up your Firebase project to handling authenticated states in your React components.

What You'll Learn

  • Setting up Firebase project and authentication - Create and configure your Firebase project to support Google Sign-In
  • Configuring Google Cloud Console credentials - Generate OAuth 2.0 client IDs for secure authentication
  • Installing and initializing Firebase SDK in React - Add Firebase packages and configure authentication in your application
  • Creating Google Sign-In button component - Build a reusable sign-in component with error handling
  • Managing user sessions with React Context - Share authentication state across your application
  • Implementing protected routes - Restrict access to authenticated users only
  • Best practices for secure authentication - Follow security guidelines and handle edge cases properly

With Firebase Authentication, you can implement secure user identity management that scales from small projects to large applications. The integration works seamlessly with React's component-based architecture and provides a foundation for building features like user profiles, personalized content, and access control. For applications built with modern React frameworks, check out our guide on Next.js layouts and nested layouts to understand how authentication integrates with page structure.

If you're building cross-platform applications, our React Native chat app tutorial demonstrates how to implement similar authentication patterns in mobile environments.

Prerequisites and Project Setup

Before adding Google Sign-In to your React app, ensure you have a React project set up and a Firebase project created. The prerequisites include Node.js installed on your machine, a React application (created with Create React App, Vite, or Next.js), and a Google account for accessing Firebase Console.

Creating a Firebase Project

The first step involves creating a Firebase project that will manage your authentication backend. Navigate to the Firebase Console, sign in with your Google account, and follow these steps:

  1. Click "Add project" and enter a name for your Firebase project
  2. Configure Google Analytics (optional but recommended for understanding user behavior)
  3. Wait for Google to set up your project resources
  4. Once created, you'll be redirected to your project dashboard

Firebase provides a free tier that includes authentication services, making it suitable for projects of all sizes. The Spark (free) plan includes unlimited Google Sign-In users and up to 49,999 monthly active users before any charges apply.

After creating your project, enable Google as an authentication provider by navigating to Authentication > Sign-in method > Google and toggling the enable switch. Configure the project name that users will see during the OAuth consent flow.

Installing Required Dependencies

Firebase provides an official JavaScript SDK that works seamlessly with React. Install the SDK using your preferred package manager. The Firebase JavaScript SDK version 9 and higher uses a modular approach for tree-shaking and smaller bundle sizes.

npm install firebase
# or
yarn add firebase

If you're using React Router for navigation in your application, ensure it's installed as well since protected routes rely on routing capabilities:

npm install react-router-dom
# or
yarn add react-router-dom

The Firebase SDK handles all communication with Google's authentication servers and provides type-safe methods for common authentication operations. After installation, verify that your package.json includes the correct version of Firebase before proceeding to configuration.

Firebase Authentication Features

Secure Identity Management

Google handles password security and credential storage, eliminating password management vulnerabilities and reducing your security burden

Cross-Platform Support

Same authentication works across web, iOS, and Android with Firebase SDK, allowing users to seamlessly switch devices

Free Tier Available

Authentication services are free for most applications with generous limits for Google Sign-In and email/password auth

Session Persistence

Automatic session management with configurable persistence options to control how long users remain signed in

Google Cloud Console Configuration

Creating authorization credentials is essential for Google Sign-In to function properly. These credentials identify your application to Google's OAuth 2.0 servers and enable secure token-based authentication between your app and Google's identity services.

Creating OAuth 2.0 Credentials

Navigate to the Google Cloud Console and create OAuth 2.0 credentials for your web application. Follow these steps to generate your client ID:

  1. Sign in with the same Google account used to create your Firebase project
  2. Navigate to APIs & Services > Credentials in the left sidebar
  3. Click "Create Credentials" and select "OAuth client ID" from the dropdown
  4. Select "Web application" as the application type
  5. Enter a descriptive name for your OAuth client (e.g., "React App - Production")
  6. Click "Create" to generate your client ID and secret

This process generates a client ID that uniquely identifies your application during the authentication flow. The client ID is safe to expose in client-side code as it's tied to specific authorized origins.

Configuring Authorized JavaScript Origins

When creating OAuth credentials, you must specify the authorized JavaScript origins where your app will run. Google validates that authentication requests originate from these trusted domains:

  • Development: http://localhost:3000 (or your specific dev port like 5173 for Vite)
  • Production: Your actual domain (e.g., https://yourapp.com)

Add all development and production origins to the authorized list. For local development, you can add multiple localhost ports if you work on different projects. For production, ensure you add both the primary domain and any subdomains used by your application.

If you deploy to multiple environments (staging, production), create separate OAuth clients for each environment to keep credentials isolated and easily revokable if needed.

firebase.js - Firebase Configuration
1import { initializeApp } from 'firebase/app';2import { getAuth, GoogleAuthProvider } from 'firebase/auth';3 4const firebaseConfig = {5 apiKey: 'YOUR_API_KEY',6 authDomain: 'YOUR_PROJECT_ID.firebaseapp.com',7 projectId: 'YOUR_PROJECT_ID',8 storageBucket: 'YOUR_PROJECT_ID.appspot.com',9 messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',10 appId: 'YOUR_APP_ID'11};12 13const app = initializeApp(firebaseConfig);14export const auth = getAuth(app);15export const googleProvider = new GoogleAuthProvider();

Firebase Authentication Setup in React

With credentials ready, set up Firebase Authentication in your React application. The initialization process involves importing Firebase, configuring it with your project credentials, and setting up the Google Sign-In provider to handle OAuth flows.

Initializing Firebase

Create a Firebase configuration file that exports the initialized Firebase app and authentication instance. This file serves as the central authentication hub for your application and should be imported wherever you need access to authentication features. Place this file in a dedicated config or firebase folder within your source directory.

The configuration object contains your project's unique credentials found in Firebase Console > Project Settings. Each field serves a specific purpose: apiKey validates requests, authDomain handles OAuth redirects, projectId identifies your Firebase project, and appId uniquely identifies your application instance.

Initialize Firebase once at the entry point of your application and export the authentication instance. The GoogleAuthProvider enables the Google Sign-In flow by configuring OAuth scopes and settings. You can customize the provider with additional parameters like hosted domain restrictions if needed.

Setting Up Authentication State Observer

Firebase provides an authentication state observer that notifies your application whenever the user's sign-in status changes. This is crucial for managing protected routes and UI updates based on authentication state throughout your component tree.

The onAuthStateChanged method sets up a listener that fires whenever Firebase detects a change in authentication state--on initial page load, after sign-in, after sign-out, or when a token expires. This observer should be set up in a React Context Provider that wraps your entire application to ensure consistent state across all components.

Always return a cleanup function from your effect that unsubscribes from the observer when components unmount. This prevents memory leaks and ensures the listener is removed when your application shuts down. The loading state prevents flash-of-content by showing a loading indicator until Firebase confirms the user's authentication status.

SignIn.jsx - Google Sign-In Component
1import { signInWithPopup } from 'firebase/auth';2import { auth, googleProvider } from './firebase';3 4const SignIn = () => {5 const handleSignIn = async () => {6 try {7 const result = await signInWithPopup(auth, googleProvider);8 const user = result.user;9 console.log('Signed in user:', user);10 // User is now signed in - redirect or update state11 } catch (error) {12 console.error('Sign-in error:', error);13 // Handle specific error codes for better user experience14 if (error.code === 'auth/popup-closed-by-user') {15 console.log('User closed the sign-in popup');16 }17 }18 };19 20 return (21 <button onClick={handleSignIn}>22 Sign in with Google23 </button>24 );25};26 27export default SignIn;

Managing User Sessions with React Context

Using React's Context API provides a clean way to share authentication state across your application without prop drilling through multiple component layers. Create an AuthContext that wraps your application and provides user data and authentication functions to all components that need them.

Creating an Auth Context

The AuthContext manages the user's authentication state and provides functions for signing in and out. This pattern centralizes authentication logic in one place and makes it accessible throughout your component tree without passing props manually at every level.

Create the context using createContext and define a custom hook useAuth that provides a simple interface for components to access authentication state. The AuthProvider component sets up the authentication state observer when mounted and cleans up the subscription when unmounted to prevent memory leaks.

The provider renders children only after Firebase has determined the user's authentication status. This prevents unauthenticated users from briefly seeing protected content before being redirected. The loading state can be used by components to show loading indicators while authentication is being initialized.

Protected Route Implementation

Implement route protection by creating a wrapper component that checks authentication state before rendering protected content. Unauthenticated users are redirected to the sign-in page while authenticated users can access the protected routes.

The ProtectedRoute component uses React Router's Navigate component to redirect users who aren't signed in. It checks both the user existence and loading state to prevent premature redirects during the initial authentication check. This pattern works with any routing solution that supports component composition and redirects.

AuthContext.jsx - Authentication Context
1import { createContext, useContext, useEffect, useState } from 'react';2import { onAuthStateChanged, signOut } from 'firebase/auth';3import { auth } from './firebase';4 5const AuthContext = createContext();6 7export const useAuth = () => useContext(AuthContext);8 9export const AuthProvider = ({ children }) => {10 const [user, setUser] = useState(null);11 const [loading, setLoading] = useState(true);12 13 useEffect(() => {14 // Subscribe to authentication state changes15 const unsubscribe = onAuthStateChanged(auth, (user) => {16 setUser(user);17 setLoading(false);18 });19 20 // Cleanup subscription on unmount21 return unsubscribe;22 }, []);23 24 const logout = () => signOut(auth);25 26 const value = { user, loading, logout };27 28 return (29 <AuthContext.Provider value={value}>30 {!loading && children}31 </AuthContext.Provider>32 );33};
ProtectedRoute.jsx - Route Protection
1import { Navigate } from 'react-router-dom';2import { useAuth } from './AuthContext';3 4const ProtectedRoute = ({ children }) => {5 const { user, loading } = useAuth();6 7 // Show loading state while Firebase initializes8 if (loading) {9 return <div>Loading...</div>;10 }11 12 // Redirect to sign-in if user is not authenticated13 if (!user) {14 return <Navigate to="/signin" />;15 }16 17 // User is authenticated - render protected content18 return children;19};20 21export default ProtectedRoute;

Implementing Sign-Out Functionality

Provide users with the ability to sign out of your application when they're done. Firebase's signOut method clears the user's session from the current browser and updates the authentication state throughout your application, triggering the onAuthStateChanged listener.

SignOut Component

Create a simple SignOut component that calls Firebase's signOut method through the useAuth hook and handles any errors that may occur during the process. This component can be placed in your navigation header, user menu, or settings page for easy access.

The logout function from AuthContext directly calls Firebase's signOut which invalidates the user's session token. After successful sign-out, the authentication state updates to null and any ProtectedRoute components will redirect users to the sign-in page. Error handling should address network issues and cases where the sign-out fails due to session expiration.

Consider whether you want to sign users out completely or just clear local credentials. Firebase's session persistence options determine how long credentials are stored, which affects the sign-out experience across browser sessions and tab reopens.

SignOut.jsx - Sign Out Component
1import { useAuth } from './AuthContext';2 3const SignOut = () => {4 const { logout } = useAuth();5 6 const handleSignOut = async () => {7 try {8 await logout();9 // Redirect to home or sign-in page after sign-out10 } catch (error) {11 console.error('Sign-out error:', error);12 }13 };14 15 return (16 <button onClick={handleSignOut}>17 Sign Out18 </button>19 );20};21 22export default SignOut;

Best Practices and Security Considerations

Implementing authentication requires careful attention to security best practices to protect user data and prevent unauthorized access. Following these guidelines ensures your implementation is robust and trustworthy.

Verifying ID Tokens on the Backend

For applications that require backend API access, verify Firebase ID tokens on your server to ensure requests come from authenticated users. This prevents unauthorized API calls and validates that tokens were issued by your specific Firebase project.

Server-side token verification involves sending the ID token from your client to your backend API, then using Firebase Admin SDK to verify the token's authenticity and decode user information. Never trust tokens sent from clients without verification, as malicious users could forge authentication claims.

Authentication State Persistence

Firebase Auth supports different session persistence modes that control how long user sessions remain active:

  • Session: Session lasts until the browser tab is closed (default for most OAuth flows)
  • Local: Session persists across browser restarts using localStorage
  • None: No persistence, requiring re-authentication on each page load

Configure persistence based on your application's security requirements. Local persistence provides convenience but increases risk if the device is compromised. Session persistence offers a balance for most web applications.

Error Handling Best Practices

Implement comprehensive error handling for authentication flows to provide a smooth user experience:

  • Network errors: Handle cases where the authentication request fails due to connectivity issues
  • User cancellation: Users may close the OAuth popup--handle this gracefully without showing errors
  • Credential mismatch: Handle cases where credentials are invalid or expired
  • Session expiration: Detect and handle expired sessions by prompting re-authentication

Security Checklist

Review these security items before deploying your authentication implementation:

  • Never expose Firebase console credentials or service account keys in client-side code
  • Configure OAuth consent screen with accurate application information in Google Cloud Console
  • Set up authorized redirect URIs to prevent authorization code interception attacks
  • Enable required Google APIs (Identity Toolkit API, Google Sign-In API) in Cloud Console
  • Implement proper error messages that inform users without exposing sensitive system details
  • Consider implementing rate limiting on authentication endpoints to prevent brute-force attacks
  • Use HTTPS in production to prevent token interception during transmission
  • Review Firebase Security Rules if using Firestore or Realtime Database for user data

Following this checklist helps ensure your authentication implementation meets security best practices and protects both your application and your users from common vulnerabilities. For comprehensive web development services that include secure authentication implementation, our team can help you build robust, scalable applications with best-in-class security practices.

Frequently Asked Questions

Is Firebase Authentication free?

Firebase Authentication offers a generous free tier that includes Google Sign-In along with other providers like email/password, phone auth, and anonymous auth. Most small to medium applications can use Firebase Auth without incurring charges. The free tier includes unlimited Google Sign-In users and up to 49,999 monthly active users per month for other authentication methods.

Can I use Google Sign-In without Firebase?

Yes, Google provides a standalone Sign-In library for web applications through the Google Identity Services SDK. However, Firebase Authentication simplifies the process by providing additional features like user management, session handling, multi-factor authentication, and seamless integration with other Firebase services such as Cloud Firestore and Cloud Functions.

How do I handle authentication in Next.js?

Next.js applications can use Firebase Auth with both client-side and server-side rendering. For client components, the implementation follows the same pattern as traditional React apps. For server components and API routes, you'll need to verify ID tokens using Firebase Admin SDK to maintain security while accessing user information on the server side.

What happens if the user revokes access?

Users can revoke app access through their Google account settings at any time. When this happens, Firebase will return an auth/account-exists-with-different-credential error on the next sign-in attempt, and your app should handle this gracefully by prompting for re-authentication or informing the user about the revoked access.

Summary

Adding Google Sign-In to your React app using Firebase Authentication provides a secure, user-friendly authentication experience that leverages Google's robust identity infrastructure. The implementation process involves several key steps that work together to create a complete authentication system.

  1. Setting up Firebase project and configuring authentication services in the Firebase Console
  2. Creating OAuth credentials in Google Cloud Console with proper authorized origins for development and production
  3. Installing Firebase SDK and initializing it with your project configuration in your React application
  4. Implementing Sign-In component using signInWithPopup method with proper error handling
  5. Managing user state with React Context and the onAuthStateChanged observer for consistent authentication state
  6. Protecting routes that require authenticated users using React Router and the useAuth hook
  7. Implementing Sign-Out functionality for session termination and clean user experience

With this foundation in place, you can extend the implementation to support additional identity providers like Facebook, GitHub, or Apple. The Firebase Authentication platform also supports email/password authentication, phone number verification, and anonymous auth for gradual conversion flows.

Next Steps

  • Add email/password authentication as an alternative sign-in method for users without Google accounts
  • Implement social login with other providers (Facebook, GitHub, Twitter) using Firebase's provider system
  • Set up Firebase Security Rules to protect user data in Firestore or Realtime Database
  • Integrate with Cloud Functions for server-side operations like sending welcome emails or tracking sign-up analytics
  • Add multi-factor authentication for enhanced security on sensitive accounts
  • Implement account linking to allow users to connect multiple authentication methods to a single account

By following the patterns and practices outlined in this guide, you can build authentication systems that are secure, scalable, and provide an excellent user experience. For teams building complex web applications, our web development services include comprehensive authentication implementation and security consulting to ensure your applications meet industry standards.

Need Help Implementing Authentication?

Our team specializes in building secure, scalable web applications with modern authentication patterns. From Firebase integration to custom identity solutions, we can help you implement authentication that works for your users.

Sources

  1. Firebase Authentication Documentation - Official Firebase documentation covering authentication setup, SDK initialization, and Google Sign-In implementation with code examples for React applications

  2. Google Identity - Web Sign-In - Google's official guide for implementing Google Sign-In, covering OAuth 2.0 credentials, button integration, and backend verification requirements

  3. Firebase Web Setup - Official Firebase guide for installing and configuring the JavaScript SDK in web applications including React