This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@insights.ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@insights.ignek.com
    • +91 6351576580
    • info@insights.ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@insights.ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@insights.ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Google, Facebook, and OTP Login Integration using Firebase in React : Part – 3

  • ReactJS
  • November 25, 2025

Share On :

Introduction

This final part completes our authentication system by adding phone/SMS verification. Building on the architecture from Part 1 (Google Auth) and Part 2 (Facebook Auth), we’ll implement secure phone number authentication with OTP verification.

Phone authentication provides :

  • Universal accessibility (no social media accounts required).
  • High security through device possession.
  • Global reach across all countries.
  • Two-factor authentication foundation.
Prerequisites
  • Completed authentication foundation from Part 1.
  • Firebase project with phone authentication enabled.
  • Understanding of reCAPTCHA integration.
Firebase Phone Authentication Setup

Step 1 : Enable Phone Authentication

  1. Firebase Console → Authentication → Sign-in method.
  2. Click “Phone” → Enable.
  3. Add authorized domains (localhost + your domain).

Step 2 : Configure Test Phone Numbers (Optional)

For development testing:

  1. Scroll to “Phone numbers for testing”.
  2. Add: Phone +917575757575, Code 123456.
  3. Use these credentials during development.
Update Components

Update Authentication Service

Extend src/services/authService.ts with phone authentication :

				
					// Add this import after other imports 
import { signInWithPhoneNumber, RecaptchaVerifier, ConfirmationResult } from 'firebase/auth';

class AuthService {
  private recaptchaVerifier: RecaptchaVerifier | null = null;
  private confirmationResult: ConfirmationResult | null = null;

  // ... existing Google/Facebook methods

  // Initialize reCAPTCHA verifier
  initializeRecaptcha(containerId: string): void {
    if (this.recaptchaVerifier) {
      this.recaptchaVerifier.clear();
    }

    this.recaptchaVerifier = new RecaptchaVerifier(auth, containerId, {
      size: 'invisible',
      callback: () => {
        console.log('reCAPTCHA solved');
      },
      'expired-callback': () => {
        console.log('reCAPTCHA expired');
        throw new Error('reCAPTCHA expired, please try again');
      }
    });
  }

// Send OTP to phone number
  async sendOTP(phoneNumber: string): Promise<void> {
    if (!this.recaptchaVerifier) {
      throw new Error('reCAPTCHA not initialized');
    }

    // Validate phone number format
    const phoneRegex = /^\+[1-9]\d{1,14}$/;
    if (!phoneRegex.test(phoneNumber)) {
      throw new Error('Please enter a valid phone number with country code');
    }

    try {
      this.confirmationResult = await signInWithPhoneNumber(
        auth,
        phoneNumber,
        this.recaptchaVerifier
      );
    } catch (error: any) {
      console.error('Send OTP error:', error);
      //You can handle specific errors here
  }

  // Verify OTP code
  async verifyOTP(code: string): Promise<AuthUser | null> {
    if (!this.confirmationResult) {
      throw new Error('No OTP request found. Please request a new code');
    }

    // Validate OTP format
    if (!/^\d{6}$/.test(code)) {
      throw new Error('OTP must be exactly 6 digits');
    }

    try {
      const result = await this.confirmationResult.confirm(code);
      this.cleanup(); // Clear after successful verification
      return this.formatUser(result.user);
    } catch (error: any) {
      console.error('Verify OTP error:', error);
      }
  }

  // Cleanup phone auth resources
  private cleanup(): void {
    if (this.recaptchaVerifier) {
      this.recaptchaVerifier.clear();
      this.recaptchaVerifier = null;
    }
    this.confirmationResult = null;
  }

// ... rest of existing methods remain same
}

				
			

Update Authentication Service

Extend src/services/authService.ts with phone authentication :

				
					// Update AuthContextType interface

interface AuthContextType {
  // ... existing properties
  sendOTP: (phoneNumber: string) => Promise<void>;
  verifyOTP: (code: string) => Promise<void>;
  initializeRecaptcha: (containerId: string) => void;
}

// Add to AuthProvider component
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  // ... existing state and effects
const sendOTP = async (phoneNumber: string): Promise<void> => {
    try {
      setError(null);
      await authService.sendOTP(phoneNumber);
    } catch (error: any) {
      setError(error.message);
      throw error;
    }
  };

  const verifyOTP = async (code: string): Promise<void> => {
    try {
      setError(null);
      setLoading(true);
      await authService.verifyOTP(code);
    } catch (error: any) {
      setError(error.message);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const initializeRecaptcha = (containerId: string): void => {
    authService.initializeRecaptcha(containerId);
  };

  const value = {
    // ... existing values
    sendOTP,
    verifyOTP,
    initializeRecaptcha
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

				
			

Phone Authentication Component

Create src/components/PhoneAuth.tsx :

				
					// PhoneAuth.tsx
import { useAuth } from "../../contexts/AuthContext";
import authService from "../../services/authService";

// Phone Authentication with OTP using Firebase
const PhoneAuth: React.FC = () => {
  const { sendOTP, verifyOTP } = useAuth(); // functions from AuthContext
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [phoneNumber, setPhoneNumber] = useState("");
  const [otpCode, setOtpCode] = useState("");
  const [step, setStep] = useState<0 | 1>(0); // 0 = enter phone, 1 = enter OTP

  useEffect(() => {
    // Initialize invisible reCAPTCHA once
    authService.initializeRecaptcha("recaptcha-container");
  }, []);

  // Step 1: Send OTP to the entered phone number
  const handleSendOTP = async () => {
    if (!/^\+[1-9]\d{1,14}$/.test(phoneNumber)) {
      return setError("Enter a valid phone number with country code (e.g., +1234567890)");
    }
    setLoading(true); setError(null);
    try {
      await sendOTP(phoneNumber);
      setStep(1); // move to OTP step
    } catch (e: any) {
      setError(e?.message || "Failed to send OTP");
    } finally {
      setLoading(false);
    }
  };

  // Step 2: Verify the OTP entered by user
  const handleVerifyOTP = async () => {
    if (otpCode.length !== 6) return setError("OTP must be 6 digits");
    setLoading(true); setError(null);
    try {
      await verifyOTP(otpCode);
      // At this point user is authenticated
    } catch (e: any) {
      setError(e?.message || "Invalid OTP code");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box>
      {step === 0 ? (
        // Phone Number Input
        <>
          <TextField
            label="Phone Number"
            placeholder="+1234567890"
            value={phoneNumber}
            onChange={(e) => setPhoneNumber(e.target.value)}
            disabled={loading}
          />
          <Button
            variant="contained"
            onClick={handleSendOTP}
            disabled={loading || !phoneNumber.trim()}
          >
            {loading ? "Sending OTP..." : "Send OTP"}
          </Button>
        </>
      ) : (
        // OTP Verification Input
        <>
          <Typography variant="body2" sx={{ mb: 2, textAlign: "center" }}>
            Enter the code sent to <strong>{phoneNumber}</strong>
          </Typography>
          <TextField
            label="OTP Code"
            value={otpCode}
            onChange={(e) => setOtpCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
            disabled={loading}
            />
          <Button
            variant="contained"
            onClick={handleVerifyOTP}
            disabled={loading || otpCode.length < 6}
          >
            {loading ? "Verifying..." : "Verify"}
          </Button>
          <Button size="small" onClick={handleSendOTP} disabled={loading}>
            Resend OTP
          </Button>
        </>
      )}
      {/*  reCAPTCHA container (required by Firebase) */}
      <div id="recaptcha-container" style={{ display: "none" }} />
    </Box>
  );
};

export default PhoneAuth;

				
			

Update Authentication Container 

Update src/components/auth/AuthenticationContainer.tsx :

				
					// AuthenticationContainer.tsx
//Existing imports..
import PhoneAuth from "./PhoneAuth";

const AuthenticationContainer: React.FC = () => {
  return (
      //In this after FacebookAuth add Below line
      <PhoneAuth />
  );
};
//Other things remain as it is

				
			

These are the primary alterations in your code to instantiate phone authentication logic in your application as it currently exists. You may customize the Dashboard and main App files as per your design, but the code logic should remain as established.

Phone Authentication Key Concepts
  • reCAPTCHA Verification :

Firebase requires reCAPTCHA to prevent spam and abuse :

    • Invisible : Runs automatically in background.
    • Visible : Shows challenge when needed.
    • Required : Cannot be disabled for phone auth.
  • Two-Step Process
    1. Send OTP : Validates phone number and sends SMS.
    2. Verify OTP : Confirms user has access to the device.
  • Phone Number Format :

Always use E.164 format : +[country code] [phone number]

    • US : +1234567890
    • UK : +441234567890
    • India : +911234567890
Security Considerations
  • Rate Limiting :

Firebase automatically limits OTP requests to prevent abuse :

    • Maximum 5 SMS per phone number per hour.
    • Exponential backoff for repeated failures.
  • Test Phone Numbers

Use Firebase test numbers in development :

				
					// Add to Firebase console for testing
testNumbers: {
  '+15555555555': '123456',
  '+15555555556': '654321'
}

				
			

Production Best Practices :

  1. Monitor Usage : Track SMS costs and usage patterns.

  2. Implement Retry Logic : Handle network failures gracefully.

  3. User Education : Clear instructions for international numbers.

  4. Fallback Options : Provide alternative auth methods.

Common Issues and Solutions

reCAPTCHA Not Loading :

				
					// Ensure proper initialization
useEffect(() => {
  const timer = setTimeout(() => {
    initializeRecaptcha('recaptcha-container');
  }, 1000);
  return () => clearTimeout(timer);
}, []);

				
			

SMS Not Received :

  • Check phone number format.

  • Verify carrier compatibility.

  • Consider regional restrictions.

  • Implement resend functionality.

Complete Authentication System :

You now have a comprehensive authentication system with :

  1. Google OAuth : Social login with Google accounts.

  2. Facebook OAuth : Social login with Facebook accounts.

  3. Phone/SMS : Universal authentication via phone numbers.

  4. Unified Architecture : Consistent error handling and user experience.

You can check out the complete code for this part in my GitHub repository here :

https://github.com/Ridham-K/Blog-Code-Examples/tree/main/firebase-auth-demo

Conclusion

The modular architecture created in Part 1 provided for a seamless addition of phone authentication, demonstrating the importance of properly structured authentication services. Your application now offers three of the main authentication methods available while remaining clean and maintainable. 

This three-part series has provided a production-ready authentication system able to provide for the differing kinds of requirements of modern web applications.

Loading...

Related Blogs

November 25, 2025
Google, Facebook, and OTP Login Integration using Firebase in React : Part - 1
Google, Facebook, and OTP Login Integration using Firebase in React : Part - 1
November 25, 2025
Google, Facebook, and OTP Login Integration using Firebase in React : Part - 2
Google, Facebook, and OTP Login Integration using Firebase in React : Part - 2
March 27, 2024
ReactJS Performance Tuning
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform _ User-Friendly, Secure, and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal
June 19, 2024
Music License Management Portal _ Onboarding & Data Integrity
Music License Management Portal : Onboarding & Data Integrity

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@insights.ignek.com
  • info@insights.ignek.com
SALES
  • sales@insights.ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@insights.ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2026 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram