How to authenticate phone number using firebase in ReactJS ?
Last Updated :
02 Nov, 2023
User authentication is a critical aspect of many web applications, and phone number authentication has become increasingly popular for its convenience and security. Firebase, a powerful platform developed by Google, offers various authentication methods, including phone number authentication.
Prerequisites
Approach
To authenticate phone numbers using Firebase in React JS we will install the Firebase module and configure the credentials. Create a login form component that accepts the phone number and authenticate it using the Firebase.
Steps to create React Application
Step 1: Create a React myapp using the following command:
npx create-react-app myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command:
cd myapp
Project Structure:

Step 3: After creating the ReactJS application, Install the firebase module using the following command:
npm i --save firebase@8.3.1 react-firebase-hooks
Dependencies list after installing packages
{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"firebase": "^8.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-firebase-hooks": "^5.1.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}
Step 4: Go to your firebase dashboard and create a new project and copy your credentials.
const firebaseConfig = {
apiKey: "your api key",
authDomain: "your credentials",
projectId: "your credentials",
storageBucket: "your credentials",
messagingSenderId: "your credentials",
appId: "your credentials"
};
Example: It shows alogin form acception number input to authenticate using the firebase by sending an OTP.
JavaScript
// Filename - App.js
import React from "react";
import { auth } from "./firebase";
import { useAuthState } from "react-firebase-hooks/auth";
import Login from "./login";
import Mainpage from "./main";
function App() {
const [user] = useAuthState(auth);
return user ? <Mainpage /> : <Login />;
}
export default App;
JavaScript
// Filename - main.js
import React from "react";
import { auth } from "./firebase";
const Mainpage = () => {
const logout = () => {
auth.signOut();
};
return (
<div style={{ marginTop: 250 }}>
<center>
<h3>
WelcomeÂ
{auth.currentUser.phoneNumber}
</h3>
<button
style={{ marginLeft: "20px" }}
onClick={logout}
>
Logout
</button>
</center>
</div>
);
};
export default Mainpage;
JavaScript
// Filename - login.js
import React, { useState } from "react";
import { firebase, auth } from "./firebase";
const Login = () => {
// Inputs
const [mynumber, setnumber] = useState("");
const [otp, setotp] = useState("");
const [show, setshow] = useState(false);
const [final, setfinal] = useState("");
// Sent OTP
const signin = () => {
if (mynumber === "" || mynumber.length < 10) return;
let verify = new firebase.auth.RecaptchaVerifier(
"recaptcha-container"
);
auth.signInWithPhoneNumber(mynumber, verify)
.then((result) => {
setfinal(result);
alert("code sent");
setshow(true);
})
.catch((err) => {
alert(err);
window.location.reload();
});
};
// Validate OTP
const ValidateOtp = () => {
if (otp === null || final === null) return;
final
.confirm(otp)
.then((result) => {
// success
})
.catch((err) => {
alert("Wrong code");
});
};
return (
<div style={{ marginTop: "200px" }}>
<center>
<div
style={{
display: !show ? "block" : "none",
}}
>
<input
value={mynumber}
onChange={(e) => {
setnumber(e.target.value);
}}
placeholder="phone number"
/>
<br />
<br />
<div id="recaptcha-container"></div>
<button onClick={signin}>
Send OTP
</button>
</div>
<div
style={{
display: show ? "block" : "none",
}}
>
<input
type="text"
placeholder={"Enter your OTP"}
onChange={(e) => {
setotp(e.target.value);
}}
></input>
<br />
<br />
<button onClick={ValidateOtp}>
Verify
</button>
</div>
</center>
</div>
);
};
export default Login;
JavaScript
// Filename - firebase.js
import firebase from 'firebase';
const firebaseConfig = {
// Add your firebase credentials
apiKey: "your api key",
authDomain: "your credentials",
projectId: "your credentials",
storageBucket: "your credentials",
messagingSenderId: "your credentials",
appId: "your credentials"
};
firebase.initializeApp(firebaseConfig);
let auth = firebase.auth();
export { auth, firebase };
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Similar Reads
How to authenticate firebase with GitHub in ReactJS ?
The following approach covers how to authenticate firebase with GitHub in react. We have used the firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React app using the following command: npx create-react-app gfgappStep 2: After creating your project fo
3 min read
How to authenticate with google using firebase in React ?
The following approach covers how to authenticate with Google using firebase in react. We have used firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React myapp using the following command: npx create-react-app myappStep 2: After creating your project
3 min read
How to Create Phone numbers and Contacts List in ReactJS ?
This article will guide you through creating a Contacts Manager application in React, styled with Bootstrap and enhanced with Font Awesome icons. The application will allow you to add, edit, and delete contacts using modal dialogs. Approach:Create a new React project using create-react-app.Create a
4 min read
Google SignIn using Firebase Authentication in ReactJS
Firebase simplifies mobile and web app development by offering pre-built features like user authentication (email/password, Google Sign-In, etc.) without the need to build complex backends. This saves time and resources for developers.In this article, we will discuss about the Google Sign-In feature
4 min read
How to get current date and time in firebase using ReactJS ?
This article provides a detailed walkthrough on obtaining the current date and time in a Firebase environment using ReactJS. Readers will gain insights into the implementation process, enabling date and time functionalities into their React projects powered by Firebase. Prerequisites:Node JS or NPMR
2 min read
How to Authenticate with Google using Firebase in React Native Application ?
In this article, we will discuss how can we authenticate with Google using Firebase in React Native. Creating React Application And Installing ModuleCreate a React app using the following command: npx react-native@latest init AwesomeProjectProject StructureNow install required npm packages: npm i @r
2 min read
Firebase Authentication with Phone Number OTP in Flutter Web
Phone number verification using Firebase in the Flutter Web app can be done by sending OTP SMS to the phone number. The user will enter the OTP in the message and will easily sign in to his/her account. We are going to implement it in Flutter Web. Step by Step implementation Step 1: Create a new Flu
4 min read
How to get meta data of files in firebase storage using ReactJS ?
Within the domain of web development, effective file management is a frequent necessity, and Firebase Storage emerges as a resilient solution. This article explores the nuances of extracting metadata from files housed in Firebase Storage through the lens of ReactJS. PrerequisitesNode JS or NPMReact
2 min read
How to push data into firebase Realtime Database using ReactJS ?
Firebase is a popular backend-as-a-service platform that provides various services for building web and mobile applications. One of its key features is the Realtime Database, which allows developers to store and sync data in real-time. In this article, we will explore how to push data into the Fireb
2 min read
Anonymous authentication in firebase using React JS
This method explains how to sign in without revealing your identity using Firebase in a React app. It's like having a secret entry you create and use temporary anonymous accounts for logging in. We make it happen by using the special tools provided by Firebase. Prerequisites:React JSFirebaseApproach
3 min read