Hello everyone, my name is Rohit and welcome to
my channel. In this video, I will show you how to use phone authentication in Next.js application
with Firebase. The UI will be simple because my main goal is to show you guys how to send the OTP
using the Firebase backend. Follow the video and don't skip any part. If you face any issues, then
feel free to comment here or DM me on my social media handles. The links are in the description
So, without any further delay, let's get started! I started a Next.js app, and these are
my default settings for this project. My project name is firebase-auth.
Next, navigate to the firebase-auth directory and install the Firebase package
using the command: npm install firebase. Next, I opened the app in Visual Studio Code and, without writing any code, I ran the
project using the command: npm run dev. Before writing the project code, let's
set up our Firebase app. To do this, go to Google and search for Firebase. Click on
the first link to the Firebase website. Setting up a Firebase account is very easy, just
follow the video and you'll be good to go. Click on Web, and name your application here. We're going to use these config
keys in our project. To do this, create a file called config.js inside the app
directory and copy and paste these keys into it. Modify the code to meet your
requirements. For example, since we're going to use authentication, we
need to import the Firebase Auth library. Now, in the Build section, click
on Authentication and then click on Get Started. Here, you just need to
enable the Phone Authentication service. Okay, now go back to the app directory and
create a file called login.js inside it. This is a component that will contain all the
phone auth login code using Firebase. Later, we'll import this component into the page.js file. —-----
We begin by importing necessary modules and libraries. React
is the core library for building user interfaces, and we're using hooks like useState and
useEffect to manage component state and lifecycle. We also import specific Firebase
authentication methods and configurations. Here, we initialize some state variables using
the useState hook. phoneNumber and otp are for storing the phone number and OTP input values.
confirmationResult will hold the result of the OTP confirmation, and otpSent is a boolean flag
to track whether the OTP has been sent or not. We create instances of the
Firebase authentication and Next.js router using getAuth
and useRouter respectively. This is how we use the useEffect hook to run
a function after the component renders. This function will create a reCAPTCHA verifier object
and assign it to the window.recaptchaVerifier property. A reCAPTCHA verifier is a widget
that verifies that the user is not a robot by asking them to solve a challenge. We need to
use a reCAPTCHA verifier to prevent abuse of the phone number and OTP authentication feature.
The second argument of the useEffect hook is an array of dependencies, which tells React to only
run the function when the auth object changes. The handlePhoneNumberChange and handleOTPChange functions will update the phoneNumber and
otp state variables with the user’s input. The handleSendOTP function will use
the signInWithPhoneNumber function from Firebase Authentication to send
an OTP to the user’s phone number and store the confirmation result in the
confirmationResult state variable. The handleOTPSubmit function will use the
confirm function from the confirmation result to verify the OTP entered by the user and
sign them in. If the sign-in is successful, the function will use the router object to
navigate the user to the dashboard page. A div with the id of “recaptcha-container”. This is where the reCAPTCHA verifier widget
will be rendered. We only show this div if the otpSent state variable is false,
which means the OTP has not been sent yet. An input element of type “tel” that lets
the user enter their phone number with country code. The value of this element is
bound to the phoneNumber state variable, and the onChange event of this element is
bound to the handlePhoneNumberChange function. An input element of type “text” that
lets the user enter the OTP they received. The value of this element
is bound to the otp state variable, and the onChange event of this element
is bound to the handleOTPChange function. A button element that lets the
user either send or submit the OTP, depending on the value of the otpSent state
variable. The onClick event of this element is bound to either the handleSendOTP or
the handleOTPSubmit function. The text and the background color of this element are
also determined by the value of the otpSent state variable.
—------------- Now, go to the page.js file. Here
we will write the code for the user Auth state change and import the Login component. First, we are going to import all the
required components. Here I am using ‘use client’ because This is a directive
that tells the JavaScript engine to run the code in client mode, which means it
will run on the browser, not on the server. Inside the function, we obtain
a reference to the router using const router = useRouter();. This allows us to
navigate to different pages in our application. We create an auth variable by calling
getAuth(app). This initializes Firebase authentication using the 'app' configuration. Within the useEffect hook, we use
onAuthStateChanged to listen for changes in the user's authentication state. When a
user signs in, the callback function is executed, and we check if there's a user. If there
is, we redirect them to '/dashboard' using router.push('/dashboard'). This
is common in authentication flows, where you want to direct users based
on their authentication status. Finally, we return JSX, defining the
structure of the home page. We have a main container with a title "Firebase
OTP Sign-In" and a Login component. —------ After a successful login, we want the
user to automatically navigate to the dashboard page. However, we haven't created
it yet. Therefore, inside the app directory, create a dashboard folder
and a page.js file within it. For now, let’s simply return a Dashboard element. We are good to go to test our
application. If everything works fine, then we will add the sign out
button to the dashboard page. The title text looks too small. It shouldn't be. I
have definitely made a blunder. So, let's fix it. Okay! The spelling of the className was also
incorrect. Now, we are good to go, I guess. Okay!! I will quickly connect my
phone here so that you all can see the incoming OTP message from Firebase. Okay! I can't see what I'm typing. I already told
you that I compromised with the UI here. But here, simply change the theme from dark
to light in the global.css file. Okay! When I click on the send OTP button,
nothing happens. I was frustrated when I was recording this, but then I realized
that my internet was too slow. So, I have to keep trying it because
I know that my code is correct. This time, I saw the reCAPTCHA on
my screen and the console screen showed that "slow network is detected."
I know, tell me something I don't know. But on the right-hand side, you can see that I have gotten a notification with a
6-digit OTP code. Let's enter that. The OTP code was correct. And after submitting
the OTP, the app state changed and the Next.js app navigated me to the dashboard page. Everything
worked perfectly except for my internet. If you refresh the Firebase authentication
dashboard, you can see a registered user number. So, now, on the dashboard page,
let's quickly add a sign out feature. —---------------------- First, we gonna imports some modules and
components that it needs, such as React, Firebase auth, app config, and Next.js router. Next, define a function called handleLogout,
which is an async function that tries to sign out the user from the auth service,
and then redirects the user to the login page using the router. If there
is an error, it logs it to the console. JSX expression that renders the
main section of the web page, which has a heading with the text “Welcome to the
Dashboard” and a button with the text “Logout”. The button has an onClick attribute that assigns
the handleLogout function as the event handler, and a className attribute that specifies
some CSS classes that style the button. The main element also has a className attribute that
specifies some CSS classes that style the element. —-------------- After you click on logout, the app
automatically navigates you to the login page. Perfect! Let's quickly add one
more user with a different mobile number. And we are all set!!
Everything is working smoothly. Okay! That’s it for this video.
I hope you learned something new today. If you do then give this
video a thumbs up and subscribe to this channel. Thanks for watching
and see you in the next next.js video.