{"id":362521,"date":"2022-02-02T07:42:43","date_gmt":"2022-02-02T15:42:43","guid":{"rendered":"https:\/\/css-tricks.com\/?p=362521"},"modified":"2022-02-02T07:42:46","modified_gmt":"2022-02-02T15:42:46","slug":"user-registration-authentication-firebase-react","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/user-registration-authentication-firebase-react\/","title":{"rendered":"User Registration and Auth Using Firebase and React"},"content":{"rendered":"\n
The ability to identify users is vital for maintaining the security of any applications. Equally important is the code that\u2019s written to manage user identities, particularly when it comes to avoiding loopholes for unauthorized access to data held by an application. Writing authentication code without a framework or libraries available can take a ton of time to do right \u2014 not to mention the ongoing maintainance of that custom code.<\/p>\n\n\n\n
This is where Firebase<\/a> comes to the rescue. Its ready-to-use and intuitive methods make setting up effective user identity management on a site happen in no time. This tutorial will work us through on how to do that: implementing user registration, verification, and authentication.<\/p>\n\n\n\n\n\n\n\n Firebase v9 SDK<\/a> introduces a new modular API surface, resulting in a change to several of its services, one of which is Firebase Authentication. This tutorial is current to the changes in v9.<\/p>\n\n\n\n To follow along with this tutorial, you should be familiar with React, React hooks, and Firebase version 8. You should also have a Google account and Node installed on your machine.<\/p>\n\n\n Before we start using Firebase for our registration and authentication requirements, we have to first set up our Firebase project and also the authentication method we\u2019re using.<\/p>\n\n\n\n To add a project, make sure you are logged into your Google account, then navigate to the Firebase console<\/a> and click on Add project<\/strong>. From there, give the project a name (I\u2019m using \u201cFirebase-user-reg-auth\u201d) and we should be all set to continue.<\/p>\n\n\n\n You may be prompted to enable Google Analytics at some point. There\u2019s no need for it for this tutorial, so feel free to skip that step.<\/p>\n\n\n\n Firebase has various authentication methods for both mobile and web, but before we start using any of them, we have to first enable it on the Firebase Authentication page. From the sidebar menu, click on the Authentication<\/strong> icon, then, on the next page, click on Get started<\/strong>.<\/p>\n\n\n\n We are going to use Email\/Password authentication. Click on it and we will be prompted with a screen to enable it, which is exactly what we want to do.<\/p>\n\n\n\n I have already created a simple template we can use for this tutorial so that we can focus specifically on learning how to implement the functionalities. So what we need to do now is clone the GitHub repo.<\/p>\n\n\n\n Fire up your terminal. Here\u2019s what we can run from the command line:<\/p>\n\n\n\n I have also included Firebase version 9 in the dependency object of the With done that, let’s start the app with To integrate Firebase, we need to first get the web configuration object and then use it to initialize Firebase in our React app. Go over to the Firebase project page and we will see a set of options as icons like this:<\/p>\n\n\n\n Click on the web ( Enter firebase-user-auth<\/strong> as the name of the web app. After that, click on the Register app<\/strong> button, which takes us to the next step where our Copy the config to the clipboard as we will need it later on to initialize Firebase. Then click on the Continue to console<\/strong> button to complete the process.<\/p>\n\n\n\n Now, let’s initialize Firebase and Firebase Authentication so that we can start using them in our app. In the Now, paste the config we copied earlier after the imports and add the following lines of code to initialize Firebase and Firebase Authentication.<\/p>\n\n\n\n Our Next up, we\u2019re going to cover how to use the ready-to-use functions provided by Firebase to add registration, email verification, and login functionality to the template we cloned.<\/p>\n\n\n In Firebase version 9, we can build functionality for user registration with the Services are always passed as the first arguments in version 9. In our case, it’s the auth service.<\/p>\n\n\n\n To create this functionality, we will be working with the Let\u2019s start by adding a function that validates the password and confirm password inputs, checking if they are not empty and are the same: Add the following lines of code after the states in the In the above function, we return an To create the registration functionality, let’s start by making the necessary imports to the Now, add the following lines of code after the In the above function, we set a condition to call the For this to start working, let’s call the With this, we can now register a new user on our site. To test this by going over to After clicking the Register<\/strong> button, if we open the browser\u2019s console we will see details of the newly registered user.<\/p>\n\n\n Context API<\/a> is a way to share data with components at any level of the React component tree without having to pass it down as props<\/a>. Since a user might be required by a different component in the tree, using the Context API is great for managing the user state.<\/p>\n\n\n\n Before we start using the Context API, there are a few things we need to set up:<\/p>\n\n\n\nTable of Contents<\/h2>\n
\n
Setting up Firebase<\/h3>\n\n\n
<\/figure>\n\n\n\n
<\/figure>\n\n\n\n
<\/figure>\n\n\n\n
<\/figure>\n\n\nCloning and setting up the starter repo<\/h3>\n\n\n
git clone -b starter https:\/\/github.com\/Tammibriggs\/Firebase_user_auth.git\n\ncd Firebase_user_auth\n\nnpm install<\/code><\/pre>\n\n\n\npackage.json<\/code> file. So, by running the npm install<\/code> command, Firebase v9 \u2014 along with all other dependencies \u2014 will be installed.<\/p>\n\n\n\nnpm start<\/code>!<\/p>\n\n\nIntegrating Firebase into our React app<\/h3>\n\n\n
<\/figure>\n\n\n\n<\/><\/code>) icon to configure our Firebase project for the web, and we will see a page like this:<\/p>\n\n\n\n
<\/figure>\n\n\n\nfirebaseConfig<\/code> object is provided.<\/p>\n\n\n\n
<\/figure>\n\n\n\nsrc<\/code> directory of our React app, create a firebase.js<\/code> file and add the following imports:<\/p>\n\n\n\n\/\/ src\/firebase.js\nimport { initializeApp } from 'firebase\/app'\nimport {getAuth} from 'firebase\/auth'<\/code><\/pre>\n\n\n\n\/\/ src\/firebase.js\nconst app = initializeApp(firebaseConfig)\nconst auth = getAuth(app)\n\nexport {auth}<\/code><\/pre>\n\n\n\nfirebase.js<\/code> file should now look something like this:<\/p>\n\n\n\n\/\/ src.firebase.js\nimport { initializeApp } from \"firebase\/app\"\nimport { getAuth } from \"firebase\/auth\"\n\nconst firebaseConfig = {\n apiKey: \"API_KEY\",\n authDomain: \"AUTH_DOMAIN\",\n projectId: \"PROJECT_ID\",\n storageBucket: \"STORAGE_BUCKET\",\n messagingSenderId: \"MESSAGING_SENDER_ID\",\n appId: \"APP_ID\"\n}\n\n\/\/ Initialize Firebase and Firebase Authentication\nconst app = initializeApp(firebaseConfig)\nconst auth = getAuth(app)\nexport {auth}<\/code><\/pre>\n\n\n\nCreating User Registration functionality<\/h3>\n\n\n
createUserWithEmailAndPassword<\/code> function. This function takes three arguments:<\/p>\n\n\n\nRegister.js<\/code> file in the src<\/code> directory of our cloned template. What I did in this file is create three form fields \u2014 email, password, and confirm password \u2014 and input is controlled by the state. Now, let\u2019s get to business.<\/p>\n\n\n\nRegister<\/code> component:<\/p>\n\n\n\n\/\/ src\/Register.js\n\/\/ ...\n\nconst validatePassword = () => {\n let isValid = true\n if (password !== '' && confirmPassword !== ''){\n if (password !== confirmPassword) {\n isValid = false\n setError('Passwords does not match')\n }\n }\n return isValid\n}\n\n\/\/ ...<\/code><\/pre>\n\n\n\nisValid<\/code> variable which can return either true<\/strong> or false<\/strong> based on the validity of the passwords. Later on, we will use the value of this variable to create a condition where the Firebase function responsible for registering users will only be invoked if isValid<\/code> is true.<\/p>\n\n\n\nRegister.js<\/code> file:<\/p>\n\n\n\n\/\/ src\/Register.js\nimport {auth} from '.\/firebase'\nimport {createUserWithEmailAndPassword} from 'firebase\/auth'<\/code><\/pre>\n\n\n\nvalidatePassword<\/code> password function:<\/p>\n\n\n\n\/\/ src\/Register.js\n\/\/ ...\n\nconst register = e => {\n e.preventDefault()\n setError('')\n if(validatePassword()) {\n \/\/ Create a new user with email and password using firebase\n createUserWithEmailAndPassword(auth, email, password)\n .then((res) => {\n console.log(res.user)\n })\n .catch(err => setError(err.message))\n }\n setEmail('')\n setPassword('')\n setConfirmPassword('')\n}\n\n\/\/ ...<\/code><\/pre>\n\n\n\ncreateUserWithEmailAndPassword<\/code> function only when the value returning from validatePassword<\/code> is true<\/strong>.<\/p>\n\n\n\nregister<\/code> function when the form is submitted. We can do this by adding an onSubmit<\/code> event to the form. Modify the opening tag of the registration_form<\/code> to look like this:<\/p>\n\n\n\n\/\/ src\/Register.js\n<form onSubmit={register} name='registration_form'><\/code><\/pre>\n\n\n\nhttp:\/\/localhost:3000\/register<\/code> in the browser, filling in the form, then clicking on the Register<\/strong> button.<\/p>\n\n\n\n
<\/figure>\n\n\n\nManaging User State with React Context API<\/h3>\n\n\n