Search code examples
javascriptemailfirebasefirebase-authenticationverification

Firebase authentication web: how to verify email address


I'm new to Firebase Authentication for the web. I managed to get a signup form working but I am running into problems with sending the email to verify the users email address. The user is created as normal and appears in my console but no verification email is sent and I get the following error in Chrome:

Uncaught TypeError: Cannot read property 'sendEmailVerification' of null

Here is the code I have so far:

"use strict";

(function () {

    // initialize firebase
    var config = {
        apiKey: "//api key",
        authDomain: "// etc",
        databaseURL: "// etc",
        projectId: "// etc",
        storageBucket: "// etc",
        messagingSenderId: "// etc"
    };
    firebase.initializeApp(config);

    // get the login form elements from HTML
    var txtEmail = document.getElementById('txtEmail');
    var txtPassword = document.getElementById('txtPassword');
    var btnLogin = document.getElementById('btnLogin');
    var btnSignUp = document.getElementById('btnSignUp');
    var btnLogout = document.getElementById('btnLogout');

    // add login event
    btnLogin.addEventListener('click', function (e) {
        // get email and pass
        var email = txtEmail.value;
        var pass = txtPassword.value;
        var auth = firebase.auth();
        // sign in 
        var promise = auth.signInWithEmailAndPassword(email, pass);
        promise.catch(function (e) {
            return console.log(e.message);
        });
    });

    // add signup event. the signup button sends user email and pass to firebase
    btnSignUp.addEventListener('click', function (e) {
        // get email and pass
        // TODO: validate email - check it is real
        var email = txtEmail.value;
        var pass = txtPassword.value;
        var auth = firebase.auth();
        var user = firebase.auth().currentUser;

        // sign in 
        var promise = auth.createUserWithEmailAndPassword(email, pass);
        promise.catch(function (e) {
            return console.log(e.message);
        }).then(function(){user.sendEmailVerification().then(function() {
          // Email sent.
        }, function(error) {
          // An error happened.
        })
                          }); // end verification
    }); // end sign up button event listener

    // show logout button when user is logged in
    // TODO: make sure the login form clears the credentials on logout
    btnLogout.addEventListener('click', function (e) {
        firebase.auth().signOut();
    });

    // realtime authentication listener
    firebase.auth().onAuthStateChanged(function (firebaseUser) {
        if (firebaseUser) {
            console.log(firebaseUser);
            btnLogout.classList.remove('hide');
            btnSignUp.classList.add('hide');
            btnLogin.classList.add('hide');
        } else {
            console.log('not logged in');
            btnLogout.classList.add('hide');
            btnSignUp.classList.remove('hide');
            btnLogin.classList.remove('hide');
        } // end if statement
    }); // end function
})();

I haven't found a straightforward example on how to do this and the docs just provide the code but no info on where put it. I appreciate your help. Thank you.

RESOLVED: Thank you for your help. It's working now. Here's the full working code:

"use strict";

(function () {

// initialize firebase 
 var config = {
 apiKey: "",
 authDomain: "",
 databaseURL: "",
 projectId: "",
 storageBucket: "",
 messagingSenderId: ""
 };
 firebase.initializeApp(config);

// get the login form elements from HTML
 var txtEmail = document.getElementById('txtEmail');
 var txtPassword = document.getElementById('txtPassword');
 var btnLogin = document.getElementById('btnLogin');
 var btnSignUp = document.getElementById('btnSignUp');
 var btnLogout = document.getElementById('btnLogout');

// login event
 btnLogin.addEventListener('click', function (e) {
 // get email and pass
 var email = txtEmail.value;
 var pass = txtPassword.value;
 var auth = firebase.auth();
 // sign in
 var promise = auth.signInWithEmailAndPassword(email, pass);
 promise.catch(function (e) {
 return console.log(e.message);
 });
 });

// add signup event. the signup button sends user email and pass to firebase
 btnSignUp.addEventListener('click', function (e) {
 // get email and pass
 // TODO: validate email - check it is real
 var email = txtEmail.value;
 var pass = txtPassword.value;
 var auth = firebase.auth();
 var user = firebase.auth().currentUser;

// create user and sign in
 var promise = auth.createUserWithEmailAndPassword(email, pass);
 promise.then(function(user) {
 user.sendEmailVerification().then(function() {
 // Email sent.
 }, function(error) {
 // An error happened.
 });
 }); 
 }); // end sign up button event listener

// show logout button when user is logged in
 btnLogout.addEventListener('click', function (e) {
 firebase.auth().signOut();
 });

// realtime authentication listener
 firebase.auth().onAuthStateChanged(function (firebaseUser) {
 if (firebaseUser) {
 console.log(firebaseUser);
 btnLogout.classList.remove('hide');
 btnSignUp.classList.add('hide');
 btnLogin.classList.add('hide');
 } else {
 console.log('not logged in');
 btnLogout.classList.add('hide');
 btnSignUp.classList.remove('hide');
 btnLogin.classList.remove('hide');
 } // end else statement
 }); // end function
 })();

Solution

  • @Nagaraj N's solution is correct, you can also modify your code as follows:

        // sign in 
        var promise = auth.createUserWithEmailAndPassword(email, pass);
        promise.then(function(user) {// You are forgetting this reference.
          user.sendEmailVerification();
          // You can also call this.
          firebase.auth().currentUser.sendEmailVerification();
          // Email sent.
        }, function(error) {
          // An error happened.
        })`