The context.auth works in cloud, but not when using the Auth emulator. Do the firebase functions need a different configuration locally?

Viewed 120

I cannot figure out why the context.auth comes undefined when using the Firebase Emulators.

The project is split between:
Frontend: React app using the "firebase" library.
Backend: Firebase callable functions using the "firebase-admin" SDK library

Whenever I initialise the app in both, FE and BE, using the cloud credentials it all works fine:

apiKey: ...,
authDomain: ...,
databaseURL: ...,
projected: ...,
storageBucket: ...,
messagingSenderId: ...,
appId: ...,

But when I'm using the localhost configuration

projectId: "default", 
apiKey: "default", 
authDomain: "localhost",

the Firebase callable function doesn't give me the context.auth object.

export const function1 = functions.https.onCall(async (data, context) => {
...

the only way for me to get it is to decode the Bearer Token manually, like this:

export const decodeIDToken = async (originalAuth: string) => {
  let decoded = null

  if (originalAuth?.startsWith("Bearer ")) {
    const idToken = originalAuth.split("Bearer ")[1]

    try {
      decoded = await admin.auth().verifyIdToken(idToken)
    } catch (err) {
      console.log(err)
    }
  }

  return decoded
}

This is how I set up the emulators in FE:

export const functions = getFunctions(app);
export const auth = getAuth(app);
export const firestore = getFirestore(app);
export const database = getDatabase(app);

setPersistence(auth, browserSessionPersistence)

if (process.env.NODE_ENV === 'development') {
    connectFunctionsEmulator(functions, "localhost", 5001)
    connectAuthEmulator(auth, "http://localhost:9099", { disableWarnings: false })
    connectFirestoreEmulator(firestore, "localhost", 8080)
    connectDatabaseEmulator(database, "localhost", 9000);
}

Do you have any idea? Maybe that is something that is not working at all...

Cheers!

0 Answers
Related