Firebase Issue in Next JS Authentication Flow: Unconfirmed Email Causes "auth/email-already-in-use" Error to Trigger

I have encountered a perplexing issue while setting up user registration with Firebase Authentication in my Next.js application. The problem arises when I try to register a new user with an unverified email address. Instead of following the correct flow to send an email verification, the code mistakenly jumps to the catch block and triggers an "auth/email-already-in-use" error.

Background:

I am developing a web application using Next.js. I have integrated Firebase Authentication into my Next.js application for managing user registration. The registration process includes creating a new user with an email and password. After successful registration, an email verification should be sent to the user. Current Problem:

When attempting to register a new user with an unverified email address, the code incorrectly goes to the catch block and triggers an "auth/email-already-in-use" error. This behavior is unexpected because the email is not already in use; it just needs verification. Expected Outcome:

Upon registering a new user with an unverified email address, the code should send an email verification without triggering the "auth/email-already-in-use" error. Actions Taken:

I have verified that the Firebase project settings allow unverified users. I have also checked the Firebase Authentication documentation and confirmed that the code aligns with best practices for handling email verification.

    const handleRegistration = async (registerData: FormData) => {
  setIsLoading(true);
  try {
    const app = initializeApp(fireconfig);

    const auth = getAuth(app);

    if (registerData.password.length < 8) {
      setPasswordErrorMessage("Password must have at least 8 characters.");
      return;
    }

    if (passwordErrorMessage !== "") {
      setPasswordErrorMessage("");
    }

    const userCredential: any = await createUserWithEmailAndPassword(
      auth,
      registerData.email,
      registerData.password
    );
    if (!userCredential.user.emailVerified) {
      // Send email verification
      await sendEmailVerification(userCredential.user);
      toast({
        title: "Email Verification Sent. Please verify your email.",
        status: "success",
        position: "top",
        duration: null,
        isClosable: true,
      });

      const userDocRef = doc(db, "users", userCredential.user.uid);

      // Check if the user already exists in the 'users' collection
      const userDocSnapshot = await getDoc(userDocRef);

      if (!userDocSnapshot.exists()) {
        const userData = {
          firstName: registerData.firstName,
          lastName: registerData.lastName,
          email: registerData.email,
        };

        await setDoc(userDocRef, userData);
        router.push("/login");
        return;
      }
    }
  } catch (error: any) {
    if (error.code === "auth/email-already-in-use") {
      setErrorMessage("That username is taken. Try another");
    }
  } finally {
    setIsLoading(false);
  }
};

Answer №1

It seems that the email address has already been registered through Firebase Authentication.

When you attempt to use createUserWithEmailAndPassword with an email address that is already in use, it triggers the auth/email-already-in-use error. This behavior is intentional, as createUserWithEmailAndPassword should be reserved for initial user registration. Subsequent logins should be handled using signInWithEmailAndPassword.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for $http.get not requiring a return value?

I am currently developing an angular application and I have a controller that interacts with a service. The controller sends a URL to the service, which then makes a GET request to that URL and receives JSON data in return. Within this JSON data is a URI f ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

Employing the identical directive within a directive [angularjs]

My requirement is to utilize the same directive within another directive, based on a conditional parameter. However, every time I attempt to do this, it appears to enter an infinite loop. It seems like the templates are being preloaded and causing a recurs ...

I could not retrieve data from the Promise {} object

Currently, I am in the midst of developing a discord bot using discord.js. When attempting to retrieve the target user, I utilize the following code: let target = message.guild.members.fetch(id). This method yields either Promise { <pending> } if the ...

Combining React with a jQuery plugin

Utilizing the jQuery nestable plugin in my React App has been a lifesaver for meeting my business needs. Despite being aware of the potential complications that arise from mixing jQuery with React, I couldn't find the exact functionality I required in ...

text within the table is overlapping when being created dynamically in the <table> using javascript and jquery.quickflip.js

Hello everyone, I am currently working on dynamically generating a table using tabs created with jquery.quickflip.js. However, I have run into an issue where the text from one tab may overwrite values in another tab when switching between them. Below is ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Is there a way to verify user credentials on the server using FeathersJS?

Currently, my single-page app is utilizing feathers client auth and a local strategy for authentication. I have implemented various middleware routes and I am looking to verify if the user is authenticated. If not, I would like to redirect them to /. Bel ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

An API built with Mongoose, Express, and Node.js is currently only able to send a single image

I have a buffer array that needs to be converted into images and sent to the user. The issue is that the current code only sends one image: const express = require("express"); const asyncHandler = require("express-async-handler"); const ...

Having trouble loading the image source using JSON in Vue.js

var topArticle=new Vue({ el:'#toparticle', data:{topmostArticle:null}, created: function(){ fetch('topnews.json') .then(r=>r.json()) .then(res=>{this.topmostArticle=$.grep(res,functi ...

Update the color scheme of text labels and the title on a 3D bar graph created with amcharts

After creating a 3D stacked bar chart, I have successfully generated the graph using the provided code. However, I am looking to customize the appearance by changing the font color of all labels and the title to a different color. While I was able to mod ...

Eliminating divs and preserving content

Is there a way to remove certain DIV elements using jQuery or pure JavaScript without affecting the content within them? Here is an example structure: <div class="whatever_name"> <div class="whatever_name"> <h2>subtitle</h2&g ...

Clicking on an embedded YouTube video will automatically redirect you to the video's

Hey there, I've added an embedded video to my website and I'm wondering if it's possible to redirect users to a new site when they click the play button? Thanks in advance! ...

What could be causing the child view to not display the AJAX result?

An AJAX call is being made in the following manner: @Ajax.ActionLink("My Schedule", "GetSchedule", "Schedule", new { selectedDate = strToday}, new AjaxOptions { UpdateTargetId = "theTimes", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }) Th ...

Looking for a way to detect changes in a select menu using Angular?

How can I determine with the openedChange event if there have been any changes to the select box items when the mat select panel is closed or opened? Currently, I am only able to detect if the panel is open or closed. I would like to be able to detect any ...

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...

Generate a new core element featuring the top 10 users

In my app, I have a function that sorts users in the mobile_user table based on their earned points and assigns them a rank. This function is triggered every time an http request is made. Now, what I want to achieve is creating a new root node called lead ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

Unable to show the response from an HTML servlet using Ajax and qTip2

I am having an issue where I am trying to display text (or html) received from a servlet response in a qTip2 tooltip within a jsp page. Despite verifying that the servlet is being invoked and returning text using Firebug, I encountered an error when attemp ...