Login with OTP in React Native & Expo apps Using Firebase

Phone Authentication For Andriod and iOS devices

OTP authentication using react native, expo, and firebase

Project setup, Package Requirements, and Code

  • Start your expo project
  • Set up your Firebase Application for the web. We will use the config keys of the firebase web application in our project.
  • Make a JavaScript file inside the root directory of the project. I named it “config.js”. Inside this file, we will add the Firebase config keys.
  • The code of the OTP login is really simple. It goes something like this:
  • Define the state of the application using the useState hook
const [phoneNumber, setPhoneNumber] = useState('');
const [code, setCode] = useState('');
const [verificationId, setVerificationId] = useState(null);
const recaptchaVerifier = useRef(null);
  • Send the verification code.
const sendVerification = () => {
const phoneProvider = new firebase.auth.PhoneAuthProvider();
phoneProvider
.verifyPhoneNumber(phoneNumber, recaptchaVerifier.current)
.then(setVerificationId);
setPhoneNumber('');
};
  • Confirm the verification code
const confirmCode = () => {
const credential = firebase.auth.PhoneAuthProvider.credential(
verificationId,
code
);
firebase
.auth()
.signInWithCredential(credential)
.then(() => {
setCode('');
})
.catch((error) => {
// show an alert in case of error
alert(error);
})
Alert.alert(
'Login Successful. Welcome to Dashboard.',
);

};
  • That’s it. The rest is the UI part. You can see the demo of this project here.
  • If you are confused or lost, I would recommend watching a step-by-step video tutorial. Few minutes of setup and code, you will be ready to test the application.

Why do I suggest watching more videos?

I am from India and I love writing code and sharing it with the community. We all know that money is the ultimate motivation for work, and the Medium payment system uses Stripe, which has been in preview mode in India for the past 4–5 years. I waited a year on the Medium platform, but in the end, nothing worked out.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store