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

Create a custom token using firebase-admin in NodeJS


I've been following the official documentation of firebase-admin for creating a custom role. I want that my user can be a doctor or a normal user only but it gives me an error:

Unhandled Runtime Error RangeError: Maximum call stack size exceeded

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

// The Firebase Admin SDK to access Firestore.
const admin = require("firebase-admin");
admin.initializeApp({
  serviceAccountId:
    "xxxxxx",
});

exports.addMessage = functions.https.onCall((data: any, context: any) => {
  const userId = "some-uid";
  const additionalClaims = {
    role: "doctor",
    name: "Juan",
  };

  admin
    .auth()
    .createCustomToken(userId, additionalClaims)
    .then((customToken: any) => {
      // Send token back to client
      console.log(customToken);
    })
    .catch((error: any) => {
      console.log("Error creating custom token:", error);
    });
});

Solution

  • Dharmaraj commented on the problem: you're not returning anything from the function, which means no result is sent to the caller.

    exports.addMessage = functions.https.onCall((data: any, context: any) => {
      const userId = "some-uid";
      const additionalClaims = {
        role: "doctor",
        name: "Juan",
      };
    
      return admin // 👈 Add return here
        .auth()
        .createCustomToken(userId, additionalClaims)
        .then((customToken: any) => {
          // Send token back to client
          return customToken;  // 👈 Add this
        })
        .catch((error: any) => {
          // Something went wrong, send error to client
          throw new functions.https.HttpsError('failed-precondition', error); // 👈 Add this
        });
    });