Create a new user account in the backend system before proceeding with authentication using Firebase Google sign-in

Is it possible to register a user in the backend before authenticating with firebase Google sign-in?

My goal is to achieve the following steps:

  1. User clicks on "sign in with Google"
  2. User logs in with their Google account
  3. A popup closes, and the user sees a loading screen while a request is sent to the backend to register the user using the provided email
  4. If the response is successful, the user is authenticated and signed in

The issue I'm facing is that the user is immediately signed in by Firebase with a session after logging in through the popup. I am trying to delay signing in the user until the backend registration request is completed successfully.

Below is the code snippet I am currently working on:

 async function GoogleSignIn() {
        const result = firebase.auth().signInWithPopup(provider, { updateCurrentUser: false })

        // Get the signed-in user's info
        const email = result.email

        const response = await fetch(`${API_URL}/api/account/register/`, {
            method: "POST",
            headers: {
                "Content-type": "application/json",
            },
            body: JSON.stringify(email),
        });
    }

Answer №1

If you want to perform certain actions before creating or signing in a user using Firebase, you can utilize blocking functions.

Note: You will need to upgrade to the Firebase Identity Platform to use blocking functions

Take a look at the sample code snippet below.

const functions = require('firebase-functions');

// Action to take before creating a user
exports.beforeCreate = functions.auth.user().beforeCreate((user, context) => {
  const email = user.email;

  try {
    const response = await fetch(`${API_URL}/api/account/register/`, {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(email),
    });
    return response;
  } catch () {
    throw new functions.auth.HttpsError('failed-precondition');
  }
});

// Action to take before signing in a user
exports.beforeSignIn = functions.auth.user().beforeSignIn((user, context) => {
  const email = user.email;

  try {
    const response = await fetch(`${API_URL}/api/account/register/`, {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(email),
    });
    return response;
  } catch () {
    throw new functions.auth.HttpsError('failed-precondition');
  }
});

For more information, refer to the Firebase documentation.

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

Can anyone help me with integrating a search functionality inside a select tag?

I am working on a select dropdown and want to add a search box to easily filter through the available options. I know this can be done using the chosen library, but I prefer to implement it using plain JavaScript or jQuery. Does anyone have suggestions on ...

Step-by-Step Guide to Sending Push Notifications via GCM with XHR (Ajax)

I have successfully used this curl command to send notifications through the terminal. However, I am now looking for a way to trigger the notification on a button click by using an XHR request instead. curl --header "Authorization: key=AIzaSyCjrU5SqotSg ...

What is the best way to add a new div below a specific div without disrupting the existing layout of other elements on the page?

Is there a way to create a new div that appears below a specific div on a webpage, but is displayed above all other elements without affecting their positioning? Here is an example: --------------------------------------------- | | ...

Sending product identification to content_ids for Facebook Pixel tracking

Looking to implement Facebook Pixel for tracking the ViewContent event on product pages. According to Facebook, it's necessary to provide content_ids or contents along with a content_type. I assume that the content_type should always be 'product ...

The database server is not appearing on the main.js page of the client

My client's main.js file contains code that is meant to display previous form entries on the webpage, but after submitting the form, no entries appear on the HTML page. My server is running on port 7777 and the root route works in Postman, as does the ...

Learn how to hide elements on print pages conditionally in Vue.js using CSS or JavaScript

I am currently using the Vue framework to work on printing webpages for my application. I have an issue that needs a solution, which I will explain below. <template> <div id = "intro" style = "text-align:center;"> <div ...

achieving outcomes beyond iframe boundaries

I currently have an IFRAME that is responsible for loading my login page. Here is the code: <iframe src="loginForm.html"></iframe> Once the form in the IFRAME is submitted, I am looking for a way to retrieve and display the results on the p ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Tips for troubleshooting a stuck promise that won't resolve when executing a Postgres query with node-postgres

Currently, I am working on performing basic CRUD operations on a Postgres database using a Node.js application that utilizes 'pg' (node-postgres). I seem to have encountered an issue with a specific query that causes the entire application to han ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

How can you obtain the userID in the Next.js 13 application directory on the server side using next-auth?

Currently, my setup includes: nextJS: 13.1.6 nextAuth 4.19.2 The application is utilizing the new app/ directory, currently in its Beta stage. An issue I am facing involves retrieving user information on a page and performing logic based on that ...

Dynamic variable declarations in JavaScript

Imagine having an object: function obj() { this.prop1; this.prop2; this.prop3; } and a collection of these objects objects = [new obj(),new obj(),new obj()]; The goal is to smoothly loop through each object using jQuery where the class name ma ...

What is the best way to enable momentum-based scrolling for the root <html> element in iOS Safari?

We are encountering difficulties in implementing momentum-based scrolling on iOS Safari for the root <html> element. The following CSS snippet yields the desired outcome: html { height: 100%; overflow-y: scroll; } ...

Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below. <template> <div> <Hero /> <Homebooks :details="details" /> </div> </template> <s ...

When trying to pass context to the interactive node shell, an error message may appear stating "TypeError: sandbox argument must be converted to a context"

I am trying to initiate an interactive node shell with pre-initialized objects. But when I use the code below, it gives me an error: var repl = require('repl') var x = 11, y = 21 var con = {} con.x = x con.y = y repl.start('> &apo ...

Encountering difficulties reading data from a database in a Next.js/Firebase application

I am encountering a problem within a nextJS app that I developed on Firebase. In my realtime DB, I have some stored data that I want to read using a component. Below is my firebase/config.js file: import {initializeApp} from "firebase/app"; imp ...

Changing UUID from binary to text and vice versa in NodeJS

I recently started a project that transitioned to using MySQL as our database. We are working with UUID strings (such as 43d597d7-2323-325a-90fc-21fa5947b9f3), but the database field is defined as binary(16) - a 16-byte unsigned binary. Although I know th ...

Error: The property 'pathname' cannot be read, as it is null

UPDATE: Removing this section from _document did solve the issue, but why? <Link href={`/search`} prefetch={false}> <a className="d-inline-block text-center" style={{ textDecoration ...

Is it considered poor form to send as many as 100 ajax requests when loading a webpage?

My table can display up to 100 rows, sometimes even more. Is it considered a bad practice to loop through all these rows and send an AJAX post request to fetch data? I am hesitant to do this during the page load as it may significantly slow down the loadin ...

The functionality of Redux is not compatible within NEXT JS middleware

Can someone provide guidance on implementing Redux inside NEXTJS middleware? I am able to use useSelector in my index file with no issues, but I'm struggling to figure out how to utilize it in middleware. As a newcomer to Next.js, any help or suggesti ...