I'm trying to connect Instagram OAuth to Firebase through Node.js back-end. I have successfully retrieved Instagram account data including access_token which I want to exchange with firebase-admin's createCustomToken on my Node.js backend. My objective here is to generate custom token so my Angular app can do signInWithCustomToken(token) into my Firebase app. There is no problem on retrieving data from Instagram as I can print my JSON object on console.
The problem is occurred when I want to exchange my access_token to Firebase Custom Token.
I have followed this guide from Firebase Admin page for Node.js and I'm facing an error message below
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, "Invalid Firebase app options passed as the first argument to initializeApp() for the " +
Error: Invalid Firebase app options passed as the first argument to initializeApp() for the app named "[DEFAULT]". The "credential" property must be an object which implements the Credential interface.
Here is my code on related issue.
// authService.js
var fbAdmin = require('firebase-admin');
var serviceAccount = require('./key/key.json');
function createFirebaseToken(instagramID) {
// I copy & pasted this var from other class
var config = {
apiKey: "MY_FIREBASE_APIKEY",
authDomain: "MY_APP.firebaseapp.com",
databaseURL: "https://MY_APP.firebaseio.com",
storageBucket: "MY_APP.appspot.com",
};
console.log(fbAdmin.credential.cert(serviceAccount)); // serviceAccount successfully printed on console
// Error appears when executing this function
fbAdmin.initializeApp({
serviceAccount: fbAdmin.credential.cert(serviceAccount),
databaseURL: config.databaseURL
});
const uid = `instagram:${instagramID}`;
// Create the custom token.
console.log(uid);
return fbAdmin.auth().createCustomToken(uid);
}
It appears that my Node app cannot initialize a connection to firebase-admin but I have no idea the solution as I am a beginner on these technologies. Please advice.
This issue can be resolved by updating firebase-tools, firebase-functions and firebase-admin packages to the latest version.
npm install -g firebase-tools#latest
npm install firebase-functions#latest
npm install firebase-admin#latest
Refer this GitHub page for more details.
Just stumbled upon on Firebase Admin Release Notes at version 5.0.0 on May 2017 stated that serviceAccount has been removed. So instead of forcing to use serviceAccount, I use credential instead.
fbAdmin.initializeApp({
credential: fbAdmin.credential.cert({
projectId: '<APP_ID>',
clientEmail: "foo#<APP_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----\n<MY_PRIVATE_KEY>\n-----END PRIVATE KEY-----\n"
}),
databaseURL: config.databaseURL
});
Updated Answer
After continuing to work with this, it seems to be able to call admin.initializeApp() without any params, you need to make sure your `/functions nodeJs setup is up to date.
In /functions directory, run this command:
npm i --save firebase-functions#latest
Thanks to:
https://stackoverflow.com/a/49437619/2162226
.. I am still getting familiar with all the nodeJS/npm details - not sure why, but seems I had to run it a few times for everything to get into place. That and the sudo npm install -g firebase-tools updated as well .
According to official docs, we need to be using at least version Firebase 4.12.0 in order to get the latest cloud functions support: https://firebase.google.com/docs/functions/callable
First Answer
I ran into the same error message in trying to set up Cloud Functions for Firebase.
Passing in the argument for admin.initializeApp solved it for my project:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
After a good amount of search, gratefully found this thread with a post where it has that line of code: https://github.com/firebase/firebase-functions/issues/99 .. because so far haven't seen it anywhere in the docs about that parameter
According to the release docs for Jan. 11, 2018:
https://firebase.google.com/support/release-notes/admin/node
The admin.initializeApp() method can now be invoked without any arguments. This initializes an app using Google Application Default Credentials, and other AppOptions loaded from the FIREBASE_CONFIG environment variable.
Kindly use the following snippet, which is mentioned in the Firebase Admin SDK for Node.js. Download the JSON file from the Service Account in the Project Settings and change the path in serviceAccount. Also add your databaseUrl, which is of the form http://app_name/.firebaseio.com
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "yourDatabaseUrl"
});
For those having this issue with "firebase-admin": "^11.0.0", you have to construct the certification passed into initializeApp() using cert imported from firebase-admin/app.
Example:
import { initializeApp, cert } from "firebase-admin/app";
const admin = initializeApp({
credential: cert({
projectId: process.env.MY_PROJECT_ID,
clientEmail: process.env.MY_PRIVATE_KEY,
privateKey: process.env.MY_CLIENT_EMAIL,
}),
});
Check what version of firebase-admin module you are using.
As per the release note of version 5.9.1
The admin.initializeApp() method can now be invoked without a credential option. The SDK uses Google Application Default Credentials when initialized this way.
release notes
Related
Hello I'm using firebase functions and I have created a Node.js project with firebase init, then I selected the options functions, firebase and storage. The project works with the firebase-admin NPM package.
When I deploy the project with firebase deploy everything goes well, but when I run the function on the cloud, it says the following message:
I have tested the entire project with the emulators and it works well.
Project Structure:
What is causing this error? Thanks!
I solved it. The problem was that I had this in the initializeApp:
const serviceAccount = require("../project-name-f3ad6ae0572f.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: BUCKET_NAME,
});
This is incorrect because I was missing the firebase configuration that is given on the Firebase Console -> Project Settings -> Your Apps.
Then, the result has to be like this:
const firebaseConfig = {
apiKey: "xxx-your-api-key-xxx",
authDomain: "project-name.firebaseapp.com",
projectId: "project-name",
storageBucket: "project-name.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxxxx",
appId: "x:xxxxxxxxxxxxxxx:web:xxxxxxxxxxxxxxx",
measurementId: "G-XXXXXXXXX",
};
admin.initializeApp(firebaseConfig);
verify your pc time, i had same problem and resolving when update pc time.
import * as admin from 'firebase-admin';
const serviceAccount = require('./firebase.json');
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
export const firebaseDB = admin.firestore();
I might be late to this question but I faced a similar issue yesterday (16 October 2022). What I figured is that, when you set your computer's time manually, firebase doesn't work.
So your firebase timestamp rules must match with your current host time.
The code for the function framework is actually public in the GoogleCloudPlatform/functions-framework-nodejs repository (although not advertised anywhere).
In particular you can see there the cases where killInstance is used, which is the one triggering exit code 16:
const killInstance = process.exit.bind(process, 16);
These cases are (at the time of writing):
· uncaughtException
· unhandledRejection
I had the same issue today, if it's only happening in your local environment, there's a 99% chance that your computer's time is wrong.
Recently, I tried to follow a few demos online to get started on a Google Firebase Cloud Functions Node.js server-side code for an application. Upon attempting to add a Firebase App (and Firestore with it),
const functions = require('firebase-functions');
const firebase = require('firebase-admin');
require('firebase/firestore');
var serviceAccount = require("<private key>.json");
const initAppFirebase = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "<URL>"
});
var db = firebase.firestore();
I begin to get this one error that mentions a missing "annotations.proto" file from the google-gax module (which is apparently imported at some point in Firestore).
Error during trigger parsing: Error occurred while parsing your function
triggers.
Error: The include `google\api\annotations.proto` was not found.
at Function.GoogleProtoFilesRoot._findIncludePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:312:11)
at GoogleProtoFilesRoot.resolvePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:298:31)
...
at v1beta1 (C:\...\functions\node_modules\#google-
cloud\firestore\src\v1beta1\index.js:30:10)
at new Firestore (C:\...\functions\node_modules\#google-
cloud\firestore\src\index.js:229:18)
I have looked around on the internet, but nobody else seems to have this problem. I just reinstalled the files, but I am still getting this issue. Removing the Firestore and Firebase initializeApp code allows it to work, so I believe it has something to do with that.
Here are my module versions from package.json
"firebase-admin": "^5.12.0",
"firebase-functions": "^1.0.1",
"firestore": "^1.1.6",
Is there a way to fix this problem (botched installation, outdated libraries, missing code/requires etc.)? Thank you very much.
EDIT: Added code and package.json for version info. I dug around in the actual file \node_modules\google-gax\lib\grpc.js and found that it tries to return a valid path leading to the import file annotation.proto by trying to test google\api\annotations.proto at each parent directory.
var current = originPath;
var found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
There is, unfortunately, no such directory, though perhaps it is looking for the annotations file in google-proto-files\google\api\annotations.proto (but adding that file in manually leads to further errors). There is also a github issue here https://github.com/googleapis/nodejs-firestore/issues/175 mentioning it.
You say that you're trying to build a web app. But the code you are using is for initializing the Firebase Admin SDK in a (server-side) Node.js script.
If you want to use Firestore in your web app, start with the code you see when you click the WEB tab on this page:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-firestore.js"></script>
And then:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
You can get the values in that initializeApp call by:
Going to the Project overview page
Click ADD ANOTHER APP
Click Add Firebase to your web app
I am facing an issue in setting up Client SDK in NodeJS.
I have already initialized both SDK in the Node Server using the following code:
const admin = require('firebase-admin');
const client = require('firebase');
const serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://*******.firebaseio.com"
});
client.initializeApp({
apiKey: "**************",
authDomain: "***********.firebaseapp.com",
databaseURL: "https://*********.firebaseio.com",
storageBucket: "**********.appspot.com"
});
const clientAuth = client.auth();
The admin SDK is working fine but when I try to add the Client SDK, it's throwing me the following error.
client.auth is not a function
I am new to firebase, so confused whether we cannot initialize both the SDK in the same Node Server
UPDATE
I have tried with the firebase v4.6.2, its working and it's not showing the error till version v4.7.0. but when I switch to the v4.8.0, the client SDK is throwing me the error. When I tried to initialize the client SDK separately in a node server it's working, so after v4.8.0 is it not recommended to use both client and admin SDK on the same node server?
The client.auth is not a function error was fixed in the v4.9.1 release on February 1st. It appears to be dependant only on the client SDK & not related to using the Admin SDK as well.
Your code should work as-is once you update.
I've created electron app that uses firebase auth and database.
App uses signInWithCustomToken with token received from remote server.
On my work machine (macOS) it works as expected. But when i've cloned my repo to home machine (windows) i've receive
FIREBASE WARNING: Provided authentication credentials are invalid.
This usually indicates your FirebaseApp instance was not initialized correctly.
Make sure your apiKey and databaseURL match the values provided
for your app at https://console.firebase.google.com/
As i found here in same questions error with firebase-admin. But i'm using client library. Also i've misunderstood how it depends on machine where it runs?
I'm using npm package firebase 4.1.5 packed with webpack into client script
Initialising:
const firebaseConf = {
apiKey: '<api_key>',
authDomain: '<domain>.firebaseapp.com',
databaseURL: 'https://<database>.firebaseio.com',
projectId: '<project_id>',
storageBucket: '<storage>.appspot.com',
messagingSenderId: '<sender_id>',
};
Vue.prototype.$firebase = firebase.initializeApp(firebaseConf);
So on work machine all database operations work fine. But on home machine it shows that warning few times after signInWithCustomToken called and does nothing else
The code is exactly the same. It was cloned from bitbucket
I've spent a whole day trying to figure out the reason but failed.
Sorry for my English
Thank you in advance
In recent days, i have encountered a few problems with my old firebase sdk's in both android and server node js 'firebase' sdk. Sending notifications and retrieving data.
After i updated android dependencies with newest version, notification problem was solved.
But in server side:
Installed firebase admin sdk.
Followed instructions:
https://firebase.google.com/docs/admin/setup
and also checked role of firebase-adminsdk service account.
Problem with the following example:
var admin = require("firebase-admin");
var serviceAccount = require("filepath.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://dbname.firebaseio.com"
});
var db = admin.database();
var ref = db.ref("myval");
ref.once("value",function(snapshot){
console.log(snapshot.val());
});
Example does not return any value or error, just waiting. Sure there is 'myval' child under main database tree.
What wrong may cause the problem?
Solved the problem with help of firebase team.
Enabling the logging before database definition with:
admin.database.enableLogging(true);
var db = admin.database();
helps for debugging. After that I got the error:
Failed to get token: Error: Error fetching access token: invalid_grant (Invalid JWT: Token must be a short-lived token and in a reasonable timeframe)
And according to this:
Authentication on google: OAuth2 keeps returning 'invalid_grant'
my machine timezone was not syncronized appropriately with a ntp server, which is required for new admin authentication in my case.
Then (in ubuntu 14.04) setting the timezone (timezones are here: '$ timedatectl list-timezones') :
$ sudo timedatectl set-timezone desired_timezone
solved the problem!
Thanks for helps.