How to get and set data to Firebase with Node.js?
I solved my problem. I just downloaded serviceAccount.json file from Firebase Console and inserted it into my project. The 'Service Account' file contains everything that I need.
var firebase = require('firebase');
firebase.initializeApp({
databaseURL: 'https://*****.firebaseio.com',
credential: 'myapp-13ad200fc320.json', // This is the serviceAccount.json file
});
Then the code below worked nicely.
firebase.database().ref('/').set({
username: "test",
email: "[email protected]"
});
This specific syntax/library for service accounts in node
apps is being deprecated. The new method of reaching firebase on a server (that is, not a consumer app, like IoT or desktop) is the firebase admin sdk
.
Your initialization code should now go:
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
You can still manually key in your credentials, but they're now assigned to a diff't property:
admin.initializeApp({
credential: admin.credential.cert({
projectId: "<PROJECT_ID>",
clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n"
}),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
We faced the same problem with AWS Beanstalk. The root cause was because \n
was replaced by \\n
in the private key variable.
After adding the replace regexp it was fixed:
"private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')
Printing the variables into the log could also help isolating the issue.