Hey there,
Thanks for your patience on this. I… can’t say for sure, to be totally honest! As you probably know from looking around the forum, we’ve seen many folks struggling with firebase-admin in their Netlify Functions. I’ve spent some time tinkering with it and did manage to get a write to a Realtime Database working. Not quite Firestore, but I’ll share what I did in case it’s helpful:
- copy/pasted the whole Google credentials JSON into an environment variable in the Netlify UI called GOOGLE_APPLICATION_CREDENTIALS
- manually bundled dependencies with the function in the site’s build command, so something like
cd functions/firebase/ && npm install && ../../ && [rest of build command]
// repo structure
src
dist
functions
|-firebase-func
|-package.json
|-firebase.js
// firebase.js
var admin = require("firebase-admin");
var serviceAccount = process.env.GOOGLE_APPLICATION_CREDENTIALS;
// note that an async/await function DOES NOT seem to work with db writes; use an old-school, non-async function
exports.handler = function (event, context) {
admin.initializeApp({
credential: admin.credential.cert({
projectId: JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS).project_id,
clientEmail: JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS).client_email,
privateKey: JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS).private_key
}),
databaseURL: "https://xxxxxxxxxxx-xxxxxxx.firebaseio.com"
});
try {
var db = admin.database()
var ref = db.ref('flowers')
var leaves = ref.child("leaves")
leaves.set({
1: "round",
2: "oval",
3: "symmetrical"
})
return {
statusCode: 200,
body: 'Success!'
}
} catch (err) {
return {
statusCode: 500,
body: err.toString()
}
}
};
Note that even though the write succeeded in the Realtime Database, the function did not return a 200 and ‘Success!’… or a 500. It returned a 502 with a timeout error at the endpoint. Maybe there’s a proper way to clean up the connection after a write? Not sure. I hope this helps! Let us know if you manage to accomplish what you wanted with Firestore.