Firebase Miniseries 1: Auth – DEV Community

Firebase auth is an authentication api that allows you to register, login and handle customers in your web site/app.

Implementing auth in your app could seem difficult, however in the event you observe these easy steps i’ll present you the way easy and fast it’s to make use of it.



Step 1 – Initializing our firebase app

Head to Firebase.com and go to the console. Create a brand new undertaking, enter a undertaking title and disable google analytics on the following slide.
As soon as your undertaking is created, on the present web page you might be redirected to, below the title: “Get began by including Firebase to your app” click on on the code icon that is known as “internet” subsequent to iOS and android. Enter a reputation to your internet undertaking, normally it needs to be known as “my-project-internet“. No want for firebase internet hosting, so simply hit proceed. On the following slide, click on proceed to console. You’ve gotten now created your first firebase app!



Step 2 – Establishing the auth

On the left sidebar, click on authentication. On the header, click on get began. We’re gonna begin with easy e-mail/password auth for now. So click on the primary possibility field known as e-mail/password, then click on allow, then hit save.
That is actually all of the configuration we have to do to arrange auth in your app.



Step 3 – Implementing the auth on our app.

The very first thing we have to do is get the firebase config code. To do this we are able to head to our firebase app. On the sidebar on the prime close to Undertaking overview, click on the settings (cog) icon and choose Undertaking Settings. Scroll down till you see SDK setup and configuration. Copy the code you see inside:

const firebaseConfig = {
  apiKey: '',
  and many others...
}
Enter fullscreen mode

Exit fullscreen mode

Create a config file inside your undertaking folder, known as firebase.js and duplicate this code in, changing your config values accordingly:

import firebase from "firebase"

const config = {
  apiKey: "fill in along with your actual values",
  authDomain: "fill in along with your actual values",
  projectId: "fill in along with your actual values",
  storageBucket: "fill in along with your actual values",
  messagingSenderId: "fill in along with your actual values",
  appId: "fill in along with your actual values"
}
const firebaseApp = firebase.initializeApp(config)

const db = firebaseApp.firestore()
const auth = firebaseApp.auth()
const storage = firebaseApp.storage()

export { db, auth, storage } 

Enter fullscreen mode

Exit fullscreen mode

Notice: in the event you get an error with firebase, its most likely some doc errors, to unravel it simply use this model of firebase npm: “firebase”: “^8.9.1”,



Login

Now in your undertaking, normally within the folder known as auth, you possibly can create 2 recordsdata, one shall be to log customers in and the opposite to create their accounts. So we are able to title the primary login.js and the second register.js. Within the Login file you possibly can copy this code in:

import { auth } from 'your/firebase.js/path' 
const handleLogin = () => { 
    auth.signInWithEmailAndPassword(e-mail, password)
    .then(() => {
      authListener()
    })
    .catch(err => {
      swap(err.code) {
        //go to firebase for full listing of error codes to show to person when their auth is wrong.
      }  
    }) 
  }

const authListener = () => {
    auth.onAuthStateChanged(person => {
      if(person) {
        setMyUser(person) //if utilizing react
      }
      else {
        setMyUser(null) //if utilizing react
      }
    })
  }
Enter fullscreen mode

Exit fullscreen mode

What occurs right here is when the person clicks on the login button that runs the operate handleLogin(), we name the firebase operate auth.signInWithEmailAndPassword, offering the person’s entered e-mail and password after which we name onAuthStateChanged() which is able to set a state which you could outline to obtain the firebase person’s information. That covers Login! Let’s check out registering a person.



Register

Inside our Register.js file let’s copy the next code:

const handleSignup = () => {
      auth.createUserWithEmailAndPassword(e-mail, password
      .then(() => {
        auth.onAuthStateChanged(person => {
          if(person) {
            person.updateProfile({
              displayName: `${firstName} ${lastName}`,
              photoURL: 'user-uploaded-img'
            })
            .then(() => { 
              navigate('/')
            })
            .catch(err => {
              console.log(err)
            })
          }
        })
      })
      .catch(err => {
        swap(err.code) {
          //swap error codes 
        }
      })
  }
Enter fullscreen mode

Exit fullscreen mode

As you possibly can see the Register file is similar to the login, the one distinction is we name a barely completely different operate from firebase’s auth API known as createUserWithEmailAndPassword(). This operate additionally takes in an e-mail and password as parameters and can create a person as soon as each values are legitimate. We then replace the person’s displayName and photoURL with values which you’ll optionally ask the person for after they create their account.



Conclusion

That is all it takes. You now have a completely functioning auth system in your app. By making use of the two features signInWithEmailAndPassword() and createUserWithEmailAndPassword() firebase auth supplies us, we are able to authenticate customers by creating their account and/or logging them in.

Add a Comment

Your email address will not be published. Required fields are marked *