When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user credentials for various purposes such as creating new documents in a 'users' collection within a firestore database. Both this stack answer and tutorial make reference to this method.

The example I am referring to, possibly utilizes firebase-ui - the authentication portion of my code appears as follows:

const firebaseAuthConfig = {
  signInFlow: 'popup',
  // Auth providers
  // https://github.com/firebase/firebaseui-web#configure-oauth-providers
  signInOptions: [
    {
      requireDisplayName: true,
      provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
      
    },
  ],
  signInSuccessUrl: '/',
  credentialHelper: 'none',
  callbacks: {
    signInSuccessWithAuthResult: async ({ user }, redirectUrl) => {


      

      const userData = mapUserData(user)
      setUserCookie(userData)

     

    },
  },
}


const FirebaseAuth = () => {
  // Do not SSR FirebaseUI, because it is not supported.
  // https://github.com/firebase/firebaseui-web/issues/213
  const [renderAuth, setRenderAuth] = useState(false)
  useEffect(() => {
    if (typeof window !== 'undefined') {
      setRenderAuth(true)
    }
  }, [])
  return (
    <div>
      {renderAuth ? (
        <StyledFirebaseAuth
          uiConfig={firebaseAuthConfig}
          firebaseAuth={firebase.auth()}
        />
      ) : null}
    </div>
  )
}

Is it possible to achieve the same result by utilizing the callbacks: {} feature during authentication? Is there an alternative approach to obtaining user credentials and passing them to a firestore collection in my application code rather than through a cloud function?

I have also observed that typically, the syntax used is

signInSuccessWithAuthResult: async(authResult) => {}
whereas the demo project uses
signInSuccessWithAuthResult: async ({ user }, redirectUrl) => {}

Could someone provide guidance on the best way forward?

Answer №1

There is no requirement to obtain "access to user credentials". Your main focus should be on ensuring that all Firebase queries are executed after the user has successfully signed in, regardless of how they sign in.

You can easily detect a user signing in by implementing an auth state observer. This observer callback will notify you when a user has completed the sign-in process.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // User is signed out.
  }
});

Once the callback receives a user object, this is when you can start querying the database based on the user's permissions. There is no need to explicitly "pass information to Firestore" to inform it about the current signed-in user - this integration happens seamlessly if you are utilizing Firebase SDKs for both Auth and Firestore.

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 a dynamic react component be inserted into a standalone HTML document without the need for file downloads or server support?

I am implementing React for a Single Page Application (SPA) project where users can customize a component's font size, color, etc., and then embed this customized component into their website. I'm looking for a way to bundle the component and pre ...

Using JQuery to parse an XML file and automatically redirecting the page if a specific attribute equals "Update"

Updated I've made some edits to clarify my request. My website is built using HTML5, CSS3, and JQuery, resulting in all content being on one page. During updates, I want the ability to set an option in a configuration file so that when users visit m ...

Is extracting the title of an image from Flickr?

I have a JavaScript code that randomly pulls single images from Flickr every time the page is refreshed. Now, I want to add a feature where the title of the image is displayed when it's hovered over. However, I've been searching for a solution fo ...

Having trouble logging JSON data from nodejs + express while serving static files through express. However, I am able to see the data when I only make a GET request for the JSON data without the static files

Currently, I am experimenting with sending data from a nodejs + express server to the front-end static files. The objective is for JavaScript (allScripts.js) on the front-end to process this data. At this stage, my aim is to log the data to the console to ...

"Utilizing VueJS XHR functionality within a versatile and reusable component

Seeking advice on best practices for improving the following scenario: I have a single global reusable component called <MainMenu>. Within this component, I am making an XHR request to fetch menu items. If I place <MainMenu> in both the heade ...

"Embedding a Highcharts web chart within a pop-up modal window

I am looking to incorporate a Highcharts web chart onto a specific part of a Bootstrap modal, while ensuring the size remains dynamic along with the modal itself. Here's what I have attempted so far: Sample HTML code: <td><a href="#">${ ...

Step-by-Step Guide on Resetting Versions in Package.json

I currently have around 20 react projects, each with their own package.json files. These package.json files contain various packages and their versions: "@material-ui/core": "4.11.4", "@material-ui/icons": "4.11.2", ...

Using AngularJS to implement modules in a single controller

Currently, I am in the process of learning Angularjs and have two separate template pages - one for login (login.html) and another for the main content (index.html). To incorporate a chart into my index.html page, I am utilizing a directive from here. Th ...

Executing Selenium tests: utilizing the webdriver.wait function to repeatedly call a promise

Currently, I am using Selenium ChromeDriver, Node.js, and Mocha for testing purposes... I am facing a dilemma at the moment: The driver.wait function seamlessly integrates with until. I have a promise, which we'll refer to as promiseA. This pro ...

What could be causing the issue with this JS code?

var feedback = {}; feedback.data = ["Great!", "See ya", "Not a fan..."]; feedback.display = function() { this.data.forEach(function(item) { console.log(feedback.display()); }); } The goal here is to showcase the content stored within the ...

Issues with Braintree webhooks and CSRF protection causing malfunction

I have successfully set up recurring payments with Braintree and everything is functioning properly. Below is an example of my code: app.post("/create_customer", function (req, res) { var customerRequest = { firstName: req.body.first_name, lastN ...

Tips for applying multiple colors to text within an option tag

I am currently struggling with adding a drop-down list to my form that displays 2 values, with the second value having a different text color (light gray). After some research, it seems like I need to use JavaScript for this customization. However, as I am ...

Ajax request triggers a page refresh

As I review the AJAX call within a React method, there are some key observations: handleActivitySubmit: function handleActivitySubmit(activity, urlActivity, callbackMy) { console.log("querying with activity: " + JSON.stringify(activity)); $.ajax ...

Exporting a module with Node.js is a crucial aspect of building

Within my custom module, I have successfully set up an export function. module.exports = function(callback) { var request = require("request") var url = "http://sheetsu.com/apis/94dc0db4" request({ url: url, json: true }, ...

Discover additional Atom extensions

I am exploring the possibility of implementing a feature in my Atom package where it can automatically detect whether specific third-party packages have been installed. Currently, my package adds configuration for one such third-party package, but I want t ...

The issue of JQuery and document ready being triggered multiple times while loading data into a control

Ever since implementing the load function to load content into a DIV upon document ready, I've noticed that all associated functions are firing multiple times (often twice, and sometimes endlessly). The scripts included in the head tag of all pages a ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

As a result of the Chrome 53 bug, the Yahoo Weather API encountered an insecure certificate causing the jQuery AJAX request to fail

For the past year, I've relied on the Yahoo Weather API to provide me with weather updates. I've been utilizing the following link to access the data: https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (SELE ...

Pattern for either one or two digits with an optional decimal point in regular expressions

Currently, I'm utilizing for input masking. I am specifically focusing on the "patterns" option and encountering difficulties while trying to create a regex expression for capturing 1 or 2 digits with an optional decimal place. Acceptable inputs: ...

Is there a way to automatically convert English numbers to Persian/Arabic as soon as a user types them into the input tag?

Currently, I am working with Vuejs and trying to hide the user's characters in an input tag and replace them with my own characters (specifically numbers). I have attempted using @onchange, Watch, as well as getters and setters within computed proper ...