The console
The Node.js code
npm install firebase-admin --save
Upload the the file you downloaded from the console to your Node project. I usually rename keys and keep them in a private folder which I add to .gitignore. This way you don’t accidentally publish your secrets to github. I’ve moved the uploaded file there, and called it fbserviceaccount.json
Now we can write some code. As usual I have a namespace to hold what I’ll need, starting with the initialization.
var fb = require("firebase-admin"); var app; ns.base = "/push"; /** * initialize firebase with SA * @return {Promise} */ ns.init = function() { app = fb.initializeApp({ credential: fb.credential.cert(require("./private/fbserviceaccount.json")), databaseURL: "https://xxx.firebaseio.com", databaseAuthVariableOverride: { uid: "zzzz" } }); // set up things we'll need ns.db = app.database(); ns.baseRef = ns.db.ref(ns.base); return ns; };
Walkthrough
app = fb.initializeApp({ credential: fb.credential.cert(require("./private/fbserviceaccount.json")), databaseURL: "https://xxx.firebaseio.com", databaseAuthVariableOverride: { uid: "zzzz" } });
- The key file is passed as an argument to fb.credential.cert which will use that as the credential property to initializeApp.
- I want to limit my access to the database to the minimum I need. Using databaseAuthVariableOverride allows me to set the node project as a particular user which i can then reference in my database rules. Back in the Firebase console under ‘rules’…
{ "rules": { ".read": "auth != null", ".write": "auth.uid === 'zzzz'" } }
- Finally, I’m only dealing with the /push section of my database with this app, so I set that up as the root reference for any reading and writing I’ll be doing.
And that’s it – I can get things going like this
FB.init();
To test it, I’ll create a method in my namespace for writing
ns.set = function(key, value) { return ns.baseRef.child(key).set(value) .then(function() { return key; }); };
And do a quick test
FB.set ("xliberation",{name:"blogpost",item:"test"}) .then((function(e) { console.log('set', e); }));
.. here we are
For more like this, see React, redux, redis, material-UI and firebase. Why not join our forum, follow the blog or follow me on Twitter to ensure you get updates when they are available.