CodexBloom - Programming Q&A Platform

implementing Google Cloud Function authentication for Firestore access using Firebase Admin SDK

👀 Views: 73 💬 Answers: 1 📅 Created: 2025-05-31
google-cloud firebase cloud-functions firestore javascript

I'm migrating some code and I'm building a feature where I'm working on a personal project and I'm stuck on something that should probably be simple... I'm stuck trying to I'm working on a personal project and I'm sure I'm missing something obvious here, but I'm currently working on a Google Cloud Function that needs to access Firestore using the Firebase Admin SDK... I've set up a basic function to retrieve user data, but I'm working with an authentication behavior. The behavior message I'm seeing is `GoogleAuthError: Unable to obtain valid credentials`. Here’s the code I’m using: ```javascript const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault(), }); exports.getUserData = async (req, res) => { try { const userId = req.params.id; const userDoc = await admin.firestore().collection('users').doc(userId).get(); if (!userDoc.exists) { return res.status(404).send('User not found'); } return res.status(200).send(userDoc.data()); } catch (behavior) { console.behavior('behavior fetching user data:', behavior); return res.status(500).send('Internal Server behavior'); } }; ``` I’ve verified that the Cloud Function is set up with the appropriate IAM roles for Firestore access. The service account used by the Cloud Function should have the `Firestore Admin` role, but it seems like the credentials aren’t being recognized. I also checked the Google Cloud SDK version: ```bash $ gcloud version Google Cloud SDK 400.0.0 ``` I tried deploying the function with the `--set-env-vars` flag to specify the `GOOGLE_APPLICATION_CREDENTIALS`, but it didn’t resolve the scenario. The environment variable points to a service account key JSON file. Could this be related to the permissions of the service account or something else I might be missing? Any insights would be greatly appreciated! I'm working on a application that needs to handle this. How would you solve this? This is part of a larger desktop app I'm building. What's the correct way to implement this? Any advice would be much appreciated. I'm working with Javascript in a Docker container on Windows 11. Thanks in advance! The stack includes Javascript and several other technologies. Has anyone else encountered this? Any examples would be super helpful.