Fixing the "Unknown error status: Error: The uid provided must be a non-empty string containing no more than 128 characters" issue in Firebase Functions is crucial for seamless performance

In my firebase application, I am attempting to create a new user by transferring data from the UI to a callable function. The process involves:

  1. Creating a user account using an email and password.
  2. Adding a display name followed by creating a profile in a user collection.
  3. Sending a confirmation email to the user; however, I encountered an error message that stated: "Unknown error status: Error: The uid must be a non-empty string with at most 128 characters."
const db = admin.firestore();
exports.createUser = functions.https.onCall((data, context) => {
    return admin.auth().createUser({
        email: data.email,
        password: data.password,
        displayName: data.displayName,
    }).then(user => {
        return db.doc('users/' + user.uid).set({
            email: data.email,
            displayName: data.displayName,
            type: data.type,
            organization: data.organization
        });
    })
        .then(user => {
            let uid = user.uid;
            if (data.type === "admin") {
                return admin.auth().setCustomUserClaims(uid, {
                    isAdmin: true,
                })
            } else {
                return admin.auth().setCustomUserClaims(uid, {
                    isAdmin: false,
                })
            }
        })
        .then(user => {
            return user.sendEmailVerification();
        })
        .catch(error => {
            new functions.https.HttpsError(error);
        });
})

Below is the code snippet from my React JS frontend:

let createUser = functions.httpsCallable('createUser')
createUser({
    email: this.state.email,
    password: this.state.password,
    displayName: this.state.name,
    type: this.state.type,
    organization: this.state.organization
})
.then(result => {
    console.log(result)
})
.catch(error => {
    console.log(error)
})

Answer №1

Upon executing the following code:

return db.doc('users/'+user.uid).set({
  email: ....});
})
.then(user => { // here, user is undefined})

The variable user, which represents the fulfillment value passed to the callback function in the then() method, is undefined because the set() method returns a Promise containing void.

To address this issue, it is necessary to store the value of uid in a variable within the preceding then() block, as illustrated in the code snippet below.


Furthermore, by utilizing:

  .then(user =>{ 
    return user.sendEmailVerification();
  })

You encounter a similar problem as mentioned earlier (undefined value of user). Moreover, the Admin SDK does not include a sendEmailVerification() method, which belongs to the client JavaScript SDK.

Instead, you can employ generateEmailVerificationLink() from the Admin SDK to generate an email verification link and send it via email (using services like Sendgrid) within a Cloud Function.

const db = admin.firestore();
exports.createUser = functions.https.onCall((data,context)=>{

  let userUid;

  return admin.auth().createUser({
    email: data.email,
    password: data.password,
    displayName: data.displayName,
  }).then(user =>{
    userUid = user.uid;
    return db.doc('users/'+userUid).set({
      email: data.email,
      displayName:data.displayName,
      type:data.type,
      organization:data.organization
    });
  })
  .then(()=>{
    if (data.type === "admin"){
      return admin.auth().setCustomUserClaims(userUid,{
        isAdmin: true,
      })
    }else{
      return admin.auth().setCustomUserClaims(userUid,{
        isAdmin: false,
      })
    }
  })
  .then(() =>{ 
    const actionCodeSettings = ....
    return admin.auth()
       .generateEmailVerificationLink(data.email, actionCodeSettings)
  })
  .then(link => {
     //The link was successfully generated.
     //Send an email to the user through an email service

     //Refer to https://github.com/firebase/functions-samples/tree/master/email-confirmation
     //or https://stackoverflow.com/questions/50205390/send-transactional-email-with-sendgrid-in-cloud-functions-firebase/50248871
  })
  .catch(error =>{
       throw new functions.https.HttpsError('unknown', error.message);
  });
})

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

Transmitting data as an array using JQuery

$('[data-toggle="mftapproveCheck"]').click(function () { var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get(); //alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") ...

Encountering an unexpected end of input error while making an API call using the fetch()

I'm looking to transition an API call from PHP to Javascript for learning purposes. Unfortunately, I can't make any changes on the API side as it's an external source. When attempting to use fetch() due to cross-origin restrictions, my scrip ...

Ways to initiate a page redirection within the componentWillReceiveProps lifecycle method

When my webpage or component generates a form and sends it to the backend API upon submission, I receive an object in return if the process is successful. This object is then added to my redux store. In order to determine whether the reducer successfully ...

Guide on diverting response from an ajax request

I have a situation where I need to redirect to a page based on a response. I have successfully made an ajax call and can handle the success part. The response contains an html page, but I'm unsure of how to redirect to that page. Below is the code I ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

What is the best way to establish a limit on the number of characters that can be entered into an input field in a React form?

Currently, I am creating a tool to check the strength of passwords based on their length. However, I am unsure of how to precisely determine if a password falls within specific length ranges such as "between 5 and 10 characters" or "between 20 and 30 cha ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

Using jQuery to toggle the selection of multiple checkboxes

Let's start fresh, no need to worry! This is simply a jQuery question ;) I am currently working on a PHP code where the user sends a query to our database. The form then displays sets of results grouped in tables, each with checkboxes to select the d ...

Retrieve an array object containing specific properties using axios

Currently, I am retrieving JSON data from an API call using axios and displaying it through Vue. This snippet shows the JSON Object logged in the console: 0: category_id: "categ1" item_name: "item1" price: 100 stock: 155 1: c ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

The initialized Javascript array solely consists of undefined elements, without any of the expected values

I was under the impression that I knew how to declare JavaScript arrays, but in this particular script, I seem to be stuck in an infinite loop of undefined elements within the array. In my code, I define three arrays containing numbers—two with multiple ...

The data from my client side AJAX request is not being received by my server side PHP script

Check out the AJAX code I've written: $("#loginbutton").click(function(){ var email = $('#email').val(); var password = $('#password').val(); $.ajax({ url: 'login.php& ...

React: When mapping an array of state objects, not all states are displayed

I'm encountering an odd problem while using React. I'm currently developing a budget tracking app that includes a total budget, a form to add new expenses, and displaying those expenses with their costs below. The cost of the new expense will als ...

Are your JavaScript scripts causing conflicts?

My bootstrap Carousel was working perfectly fine until I added a script to modify the navigation bars. The original script for the Carousel looked like this: <script> !function ($) { $(function() { $('#myCar ...

The 'classProperties' React component module is currently not enabled

Encountering an error while running my react module 'classProperties' isn't currently enabled (44:11): } 43 | // componentDidUpdate or try this > 44 | onClick = (e) => { | ^ 45 | e.preventDefault(); 4 ...

What is the proper way to use Object.entries with my specific type?

On my form, I have three fields (sku, sku_variation, name) that I want to use for creating a new product. I thought of converting the parsedData to unknown first, but it seems like a bad practice. export type TProduct = { id: string, sku: number ...

Enhance the image with interactive shapes using JavaScript or JQuery

Looking to integrate dynamic shapes such as circles, rectangles, lines, ovals, etc. into images using a jQuery plugin or JavaScript. For example: https://i.sstatic.net/zXWCF.png Similar to how dynamic text can be added by typing in a textbox, I am lookin ...

Automatically populate text fields depending on the option chosen from the drop-down menu

I'm currently developing a .asp webpage using JavaScript as the scripting language. One of the features I have is a drop-down menu with options populated from an 'agencies' table in the database. The 'agencies' table includes vario ...

Selenium Tips: Ensuring RemoteDriver Remains Connected to the Active Browser Tab

Currently working on a unique Windows application that utilizes voice commands to control web browsers. I am trying to figure out the best approach when users add tabs and modify the selected tab as needed. Unfortunately, RemoteDriver only supports swi ...