Search code examples
node.jsfirebasefirebase-authenticationgoogle-cloud-functionsfirebase-admin

Impossible to create an user from a Firebase Cloud Function with the admin SDK


I have been trying to create users from a Google Cloud Function, receiving an HTTP request containing the email and the password.

The problem is that I can´t seem to be able to use the function "createUserWithEmailAndPassword", I tried to import it the way it is done in the official tutorial: https://firebase.google.com/docs/auth/web/password-auth#web-modular-api (code found in the first section) https://github.com/firebase/snippets-web/blob/88aa8eb8210c90263eef7fe1f454cd6477a5a252/snippets/auth-next/email/auth_signup_password.js#L8-L21 (only the code)

The tutorial does not execute this code in a cloud function, so I suspect that the problem is around that but I can't find the solution.

// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const { onRequest } = require("firebase-functions/v2/https");

// The Firebase Admin SDK to access Firestore.
const { initializeApp } = require("firebase-admin/app");
const { getFirestore } = require("firebase-admin/firestore");
const { getAuth, createUserWithEmailAndPassword } = require("firebase-admin/auth");

initializeApp();

exports.createUser = onRequest(async (req, res) => {
    const auth = getAuth();
    const email = req.query.email;
    const password = req.query.password;

    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            // Signed in 
            const user = userCredential.user;
            // ...
        })
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            // ..
        });
});

When I run this code I get the following error:

functions: TypeError: createUserWithEmailAndPassword is not a function

How can I import this function if not like that ?

I tried looking in the node modules if I could find something relate to creating users with email and password but I did not find anything. I tried asking ChatGPT but it seemed lost aswell.


Solution

  • The instructions you're following are for the web client SDK, not the Admin SDK. They don't serve the same purpose, and don't have the same APIs. The web client SDK is for frontends and the Admin SDK is for backends.

    To learn how to use the Admin SDK for auth, use this documentation:

    https://firebase.google.com/docs/auth/admin

    You will want to read the section on creating a user. You will use the createUser function for that.