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

Switch out the specific content within the p tag

Looking to update the highlighted text within a p tag. The code below addresses handling new line characters, but for some reason the replacement is not working as expected. Check out the HTML snippet: <p id="1-pagedata"> (d) 3 sdsdsd random: Subj ...

What exactly does the .proxy() method do in jQuery?

Can you explain the purpose of the jQuery.proxy function in jQuery and describe the scenarios where it is most beneficial? I came across this link, but I'm struggling to grasp its concept fully. ...

Access external link without leaving current page

Dear webmasters, I am seeking advice, tools, or guidance to solve a simple problem. I have my own HTTP server that responds to HTTP requests. Example: If I visit the link: http://ip_server/link1, it performs a specific functionality If I visit the lin ...

When passing data to a controller through fetch in Codeigniter 3, the data may sometimes become null

I am facing an issue where I have data that needs to be sent from a view to a controller using fetch, but the data appears as null in the controller despite being successfully sent with a status of 200. Does anyone have a solution to ensure that the data i ...

"After executing a loop in JavaScript using jquery.ajax, the success function does not perform

Having trouble passing values from a PHP file to another function in Javascript. Even after a successful FOR LOOP, nothing seems to work within the SUCCESS block. Any suggestions? url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php'; $ ...

Oops! It seems like there is a problem with the hook call. Hooks are only allowed to be called inside a function component. This error occurred while trying

In my Next.js - TypeScript project, I'm trying to implement a Loader component that displays when the page is loading (true) and disappears when the page has finished loading (false). Below is the code I have written: LoadingContext.ts import React, ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

Step-by-Step Guide on Dividing Table Row Data into Two Distinct Tables

At present, I have created a dynamic table that retrieves data from the database using forms in Django. I'm facing an issue with this table as even though there are 7 columns, only 2 of them are visible. However, all 5 hidden columns do contain impor ...

The method of inserting a JSON dates object to deactivate specific days

I am currently utilizing a date picker component that can be found at the following link: While attempting to use the disabledDays section below, I have encountered an issue where I am unable to apply all three options. The blockedDatesData option works o ...

Learn how to apply inline styles to multiple objects within a single element using React

In my project using React, I am attempting to apply styles only to a specific element within another element. Here is an example with an h1 tag: const Header = () => { const firstName = "Ashraf"; const lastName = "Fathi"; const date = new Date() ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

Dynamic image loading in React with custom properties

I'm facing an issue while trying to display an image using the source stored in this.props.src. The correct name of the image file I want to load, "koolImg", is being output by this.props.src. I have imported the file using: import koolImg from ' ...

Examining whether an ajax call was not initiated within an Angular application

Is there a way to verify that an ajax request has not been made using Angular's $httpBackend? I attempted to use verifyNoOutstandingRequest() but it doesn't seem to be triggering test failures in version 1.1.5. Here is more information about the ...

Alter the color of textbox text using JavaScript

I have a text input field. When clicked, I want to change the text color style using JavaScript. Previously, I successfully achieved clearing the inner content of the textbox when clicked and reverting to the default version on blur. This code is currently ...

The index.html file is failing to load/render when using app.js

I am currently in the process of creating a to-do list using an older tutorial. The app.js file seems to be functioning properly, however, when I try to run it locally, all I see is a blank page instead of my HTML content. Here is the code found in the ap ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Improving JavaScript function by restructuring and eliminating conditional statements from within a loop

Looking for advice on how to refactor my function and eliminate the if statement inside the loop. Any suggestions would be helpful as I suspect the else condition is unnecessary. function quantitySum(array) { let sum = 0; for (let i = 0; i < array ...

Change the z-index of divs when clicked

When a button is clicked, I want to iterate through a group of absolutely positioned children divs with varying z-indexes. The goal is for the z-index of the currently visible div to decrease on each click, creating a looping effect where only one div is v ...

If the token is not present, redirect from the dashboard page in Next.js to the login page

As a newcomer to Next.js, I'm looking for a way to redirect from the dashboard page back to the login page if the userToken does not exist. In ReactJS, accomplishing this is simple. However, when attempting it in Next.js, I encountered an error where ...