In this article, I'm going to show you how you can implement phone number OTP authentication using firebase.
Although there are various options that exist, using which we can implement phone number authentication but firebase stands out because of its simplicity to use.
Setup firebase:
Go to your firebase console.
Click on Add Project & give it any name & continue.
Now you need to create a firebase app by clicking on the web icon (Refer to the below image)
Now on the input field just give it a name & click on Register app.
After that, you will get the firebase configs. Copy that and save it somewhere for later use.
Then go to the Authentication tab (Refer to the below image)
Click on get started and then from Sign-in providers, select Phone.
- Then click on the enable toggle button & save it.
Now open your React.js project on any code editor and install firebase using the below command :
npm install firebase
Now the last step is to connect firebase to your project.
To connect to firebase just create a file name as firebase.js (you can give it any name) and then paste the configs. It will look something like below:
import { initializeApp } from "firbase/app" import { getAuth } from "firebase/auth" const firebaseConfig = { apiKey: "AIzaSyBhTnKikP4BbFN_g3Ad5Mh8-qNfM7CT-00", authDomain: "test-hashnode.firebaseapp.com", projectId: "test-hashnode", storageBucket: "test-hashnode.appspot.com", messagingSenderId: "1040712778052", appId: "1:1040712778052:web:cb6850475818e91dab1711" }; const firebaseApp = initializeApp(firebaseConfig) const firebaseAuth = getAuth(firebaseApp)
Note: Ideally it's a best practice to use .env file to save the credentials.
Congratulations, now your setup is done !!
Signup / Login using Phone number:
Now let's come to the most important part i.e coding.
Importing functions, get the phone number of user, send OTP & verify the OTP.
import React, { useState } from "react";
import {
getAuth,
RecaptchaVerifier,
signInWithPhoneNumber,
} from "firebase/auth";
const [authVal, setAuthVal] = useState(null);
const [otp, setOtp] = useState(null);
const [otpForm, setOtpForm] = useState(false);
const auth = getAuth();
auth.languageCode = "en";
/**
* @name phoneAuth
* This function triggers captcha and sends OTP
* @param {event}
*/
const phoneAuth = (event) => {
event.preventDefault();
window.recaptchaVerifier = new RecaptchaVerifier(
"sign-in-button",
{
size: "invisible",
callback: (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
},
},
auth
);
// you can give any country code instead of +91
const phoneNumber = "+91" + authVal;
const appVerifier = window.recaptchaVerifier;
signInWithPhoneNumber(auth, phoneNumber, appVerifier)
.then((confirmationResult) => {
// OTP sent successfully
setOtpForm(true);
window.confirmationResult = confirmationResult;
})
.catch((error) => {
console.log(error.message);
});
};
/**
* @name verifyOtp
* This function verifies the OTP enterted by the user
* @param {event}
*/
const verifyOtp = (event) => {
event.preventDefault();
const code = otp;
confirmationResult
.confirm(code)
.then((result) => {
// User signed in successfully.
const user = result.user;
})
.catch((error) => {
console.log(error.message);
});
};
return (
<>
<div id="sign-in-button" />
{!otpForm ? (
<div>
<input
type="text"
label="Enter Phone Number"
onChange={(e) => {
setAuthVal(e.target.value);
}}
/>
<button onClick={phoneAuth}>SEND OTP</button>
</div>
) : (
<div>
<form>
<h2>Enter OTP</h2>
<input
type="text"
label="Enter OTP"
onChange={(e) => {
setOtp(e.target.value);
}}
/>
<button onClick={verifyOtp}> Verify OTP </button>
</form>
</div>
)}
</>
);
Explanation of the above code:
We have basically 2 main functions:
phoneAuth: This function verifies the captcha & gets the user's phone number from the state & sends the OTP to the user. And we are also changing the UI based on the otpForm state. When the OTP is sent we are changing otpForm state to show the OTP input UI to the user.
verifyOtp: As the name suggests this function verifies the OTP entered by the user and throws success or error response based on the user input.
Congratulations, you have successfully implemented phone number authentication using firebase. Thanks for reading.