Firebase Authentication: Create user with email and password

·

2 min read

Firebase Authentication: Create user with email and password

In my previous article you have seen how to setup your development environment for Firebase web v9 api. User authentication is a common use-case for most of the applications. In this article I am going to explain how easy is that to use Firebase authentication API to create an user with email and password. This will cover the following steps to achieve the use-case,

  • Authentication provider
  • Service implementation
  • UI integration

    Authentication provider

    Google Firebase supports different types of authentication providers. Some of the providers are as follows,
  • Email/Password
  • Phone
  • Google
  • Twitter
  • Github ... Here you will be seeing how can you use Email/Password provider for creating users. Go to your firebase console and enable the Email/Password provider under authentication. image.png

    Service implementation

    Create a service file AuthService.js under ./src/services folder
import { auth } from './firebase'; //Refer Getting started with Firebase web v9 api article
import {
  createUserWithEmailAndPassword,
} from '@firebase/auth';

export default {
  async signUpWithEmail(user) {
    console.log('AuthService.signUpWithEmail()');
    await createUserWithEmailAndPassword(auth, user.email, user.password)
    .then((credential) => {
      console.log(credential.user);
    })
    .catch((error) => {
      console.error(error);
    })
  }
};
  • 'createUserWithEmailAndPassword' is a function provided by firebase auth module which can be used to create an account with firebase. You need to pass email and password as an argument to this function.
  • 'user' is a json variable which holds email and password fields.
  • Call the 'signUpWithEmail' function in your UI layer to integrate it with your application input.

    UI integration

    Create a vue component Signup.vue and integrate the service with UI.
<template>
  <button @click="onSignup">Signup</button>
</template>

<script>
import { ref } from 'vue';
import { auth } from './services/firebase';
import AuthService from './services/AuthService';

export default {
  setup() {
    const user = {
      email: 'abc@gmail.com',
      password: 'abc#1234'
    };

    const onSignup = () => {
      AuthService.signUpWithEmail(user);
    };

    return {
      onSignup,
    }
  },
}
</script>

NOTE: I have used vue.js based code for the integration.

Did you find this article valuable?

Support Tham by becoming a sponsor. Any amount is appreciated!