How to Set Up Firebase Phone Authentication Directly on Webflow (No Third Parties)
NeWwave Blogs
Tech

How to Set Up Firebase Phone Authentication Directly on Webflow (No Third Parties)

by
neWwave
January 24, 2025

In this blog, you will quickly learn how to directly establish Firebase phone authentication on Webflow in Cambodia without using any third-party solutions, just with some custom coding.

Hello, we are neWwave Cambodia, the first No Code Low Code Agency in Cambodia. We're here to bring new innovations, tips, tricks, and insights into the No Code and Low Code space, while striving to become one of the top software development companies in Cambodia.

Before starting, we assume that you have already set up Firebase with your website domain authorized and already have existing website pages to input the phone number and handle verification.

Phone Authentication Setup

1.Go to Firebase, your project, Authentication tab

2. Go to Sign-in method, Add new provider

3.Click on Phone and enable phone authentication

4.Once enabled, you will be able to see that phone is enabled in the Sign-in method tab

Webflow Setup for the Code

To be able to send the sms verification message, we will need a way for the user to input their phone number and the otp code when they received it, thus we need 2 forms.

1.Create one form with an input field, a button, and an empty div block for the phone input

2.Make sure it’s a button and not a form button

3.Next, you need to name the all 3 elements in the Id field so that the code will be able to know which elements we are referring to. For input field Id = ‘input_phone_number’, button Id = ‘send_otp_button’, and empty div block = ‘recaptcha-container-1’.

4. Important!, the empty div block is for the recaptcha to render from the code as to avoid bots and spams. In the webflow preview, you won’t see the recaptcha but it will render once you view your website. Additionally, you don’t need to enable recaptcha in webflow.

5.Create another form with an input field and a button

6.Again, make sure it’s a button and not a form button

7.Name the input field Id = ‘input_otp’ and the button Id = ‘verify_otp_button’

The Id name for the elements can be changed accordingly to your specific use cases, but for the purpose of this blog, we will refer to these Id names in our code.

Note: The image below is when the recaptcha has been rendered in the website.

Placing the code in Webflow

Once, our pages has been set up, we can begin implementing the code. This is the complete code to be placed in the website custom code setting in Webflow. Pleas read each line of the code carefully as there are information that you need to fill for your specific website and firebase:

1.Firebase configuration

2.Url of your phone number input, verification page, and homepage

After filling all the information, you can place the code in webflow by Webflow, your website, Setting, Custom Code, and copy and paste the code into the head code field.

<script type="module">
  // Import Firebase modules
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js";
  import { getAuth, RecaptchaVerifier, signInWithPhoneNumber, PhoneAuthProvider, signInWithCredential } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-auth.js";

  // Firebase configuration (fill in your project details)
  const firebaseConfig = {
    apiKey: "...",
    authDomain: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "...",
    appId: "...",
    measurementId: "..."
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const auth = getAuth(app);

  document.addEventListener("DOMContentLoaded", () => {
    const currentUrl = window.location.href;

    // --- Send OTP Flow ---
    if (currentUrl.includes("https://place_holder/input_phone_number")) {
      const sendButton = document.getElementById("send_otp_button");
      const phoneInput = document.getElementById("input_phone_number");

      if (!sendButton || !phoneInput) return;

      window.recaptchaVerifier = new RecaptchaVerifier(
        "recaptcha-container-1",
        {
          size: "normal",
          callback: (response) => {
            sendButton.disabled = false;
          },
          "expired-callback": () => {
            sendButton.disabled = true;
          }
        },
        auth
      );

      window.recaptchaVerifier.render().then(() => {
        sendButton.disabled = false;
      });

      sendButton.addEventListener("click", async () => {
        const phoneNumberInput = phoneInput.value.trim();
        if (!/^\+\d{1,3}\d{10}$/.test(phoneNumberInput)) {
          alert("Invalid phone number format.");
          return;
        }

        try {
          const appVerifier = window.recaptchaVerifier;
          const confirmationResult = await signInWithPhoneNumber(auth, phoneNumberInput, appVerifier);
          sessionStorage.setItem("verificationId", confirmationResult.verificationId);
          alert("SMS sent successfully! Check your phone.");
          window.location.href = "https://place_holder/verification";
        } catch (error) {
          alert("Failed to send SMS.");
        }
      });
    }

    // --- Verify OTP Flow ---
    if (currentUrl.includes("https://place_holder/verification")) {
      const verifyButton = document.getElementById("verify_otp_button");
      const otpFields = document.getElementById("input_otp");

      const verificationId = sessionStorage.getItem("verificationId");
      if (!verificationId) return;

      verifyButton.addEventListener("click", async () => {
        const code = otpFields.value.trim();
        if (code.length !== 6 || !/^\d{6}$/.test(code)) {
          alert("Please enter a valid 6-digit OTP.");
          return;
        }

        try {
          const credential = PhoneAuthProvider.credential(verificationId, code);
          await signInWithCredential(auth, credential);
          alert("Phone number verified successfully!");
          window.location.href = "https://place_holder/";
        } catch (error) {
          alert("Error verifying code: " + error.message);
        }
      });
    }
  });
</script>

Understanding the code in a nutshell

This script implements phone number authentication using Firebase’s Authentication service. It begins by initializing Firebase with the project’s configuration, enabling the use of Firebase modules like authentication. The code supports two main functionalities: sending an OTP (One-Time Password) and verifying the OTP to authenticate users. When users access the phone number input page, the script initializes a reCAPTCHA verifier to ensure secure user interactions. Upon clicking the “Send OTP” button, the user’s phone number is validated, and if valid, an OTP is sent via Firebase’s sign With Phone Number method. The verification ID is stored in session storage for later use. On the OTP verification page, the code retrieves the verification ID and listens for the "Verify OTP" button click. The entered OTP is validated and, if correct, used with the stored verification ID to create a credential via PhoneAuthProvider. The credential is then used to authenticate the user with Firebase. Throughout the process, the script includes error handling and provides feedback through alerts and console logs.

After this, all you need to do is to just upload your website, and you’re done. This code will only verify the number and allow users to go through the next link when they are verified, you will need to integrate yourself if you want to use this to sign up or sign in users.

If you have any questions or issues with this code, feel free to contact us!

upward arrow to scroll to the top of the page