/firebase-tutorials

How to implement phone authentication in Firebase?

Step-by-step guide to implement phone authentication in Firebase. Set up your project, add SDKs, send SMS codes, verify them, and manage authentication state effortlessly.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to implement phone authentication in Firebase?

 

Step 1: Set Up Firebase Project

 

  1. Go to Firebase Console:
    Open Firebase Console and sign in with your Google account.

  2. Create a New Project:
    Click on 'Add Project,' and follow the instructions to create a new Firebase project.

  3. Enable Phone Authentication:
    Navigate to your project. Go to the 'Authentication' section and click on 'Sign-in method.' Enable the Phone option. You may need to enable phone number sign-in by accepting the Terms and Conditions.

 

Step 2: Add Firebase to Your App

 

  1. Add Firebase SDK:
    For Android, open your app/build.gradle file and add the Firebase authentication dependency:

    
    dependencies {
        // ...
        implementation 'com.google.firebase:firebase-auth:21.0.1'
    }
    

    For iOS, in your Podfile add:

    
    pod 'Firebase/Auth'
    
  2. Initialize Firebase in Your App:
    For Android, in your MainActivity.java or MainActivity.kt, initialize Firebase:

    
    import com.google.firebase.FirebaseApp;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Initialize Firebase
        FirebaseApp.initializeApp(this);
    }
    

    For iOS, add Firebase in your AppDelegate.swift:

    
    import Firebase
    
    func application(\_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Use Firebase library to configure APIs
        FirebaseApp.configure()
        return true
    }
    

 

Step 3: Implement Phone Number Input & Request Verification Code

 

  1. Design Phone Input UI:
    Create UI for user to enter a phone number and a button to request a verification code.

    ```html

    \`\`\`
  2. Send Verification Code:
    Implement the function to send the verification code using Firebase:

    
    function sendVerificationCode() {
        var phoneNumber = document.getElementById('phone-number').value;
        var appVerifier = new firebase.auth.RecaptchaVerifier('send-code', {
            'size': 'invisible',
            'callback': function(response) {
                // reCAPTCHA solved, allow login with phone number.
            }
        });
    
        firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
            .then(function (confirmationResult) {
                // SMS sent. Prompt user to enter the code.
                window.confirmationResult = confirmationResult;
                // Add UI for entering the verification code.
            }).catch(function (error) {
                console.error('Error during signInWithPhoneNumber', error);
            });
    }
    

 

Step 4: Implement Code Verification

 

  1. Design Verification Code UI:
    Create an area for the user to enter the verification code:

    ```html

    \`\`\`
  2. Verify the Code:
    Implement the function to verify the SMS code:

    
    function verifyCode() {
        var code = document.getElementById('verification-code').value;
        confirmationResult.confirm(code).then(function (result) {
            // User successfully signed in.
            var user = result.user;
            console.log('User signed in successfully:', user);
        }).catch(function (error) {
            console.error('Error during code verification', error);
        });
    }
    

 

Step 5: Handle Authentication State

 

  1. Observe Auth State:
    You may want to observe the authentication state to redirect users accordingly:

    
    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            console.log('User is signed in:', user);
            // Redirect to the home page or any other.
        } else {
            console.log('No user is signed in.');
            // Show login UI.
        }
    });
    
  2. Sign Out if Needed:
    Optionally, implement a sign-out function:

    
    function signOut() {
        firebase.auth().signOut().then(function() {
            console.log('User signed out successfully.');
        }).catch(function(error) {
            console.error('Sign out error:', error);
        });
    }
    

 

Step 6: Testing and Debugging

 

  • Test with Real Numbers:
    Test your phone authentication with a valid phone number to ensure the flow is working.

  • Use Firebase Authentication Debugging Tools:
    Use Firebase Console to monitor and debug authentication attempts and issues.

  • Handle and Display Errors Gracefully:
    Ensure that all errors are caught and user-friendly error messages are displayed, guiding users on how to proceed or fix issues.

 

This comprehensive guide should help you implement phone authentication in Firebase for both Android and iOS applications using JavaScript. Make sure to extensively test to ensure all aspects of the authentication function as expected.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022