How to use firebase admin SDK in local Node.js scripts? - firebase

I'm trying to use the firebase admin sdk in a local node.js script file (outside of firebase-functions) in order to preform some auth and firestore operations.
But I get this error:
{"severity":"WARNING","message":"Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail"}
Error: Failed to determine project ID: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND
Admin SDK initialization:
const admin = await import('firebase-admin');
const serviceKey = require('path/to/serviceKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceKey),
databaseURL: 'https://{project}.firebaseio.com',
});
All the questions I've found on this error are regarding running firebase-functions locally, but I'm not trying to use firebase-functions, I'm only trying to use admin.auth and admin.firestore locally.
Am I missing something here?

It works with the codes below based on this documentation:
const admin = require('firebase-admin');
const serviceKey = require('./path/to/serviceKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceKey),
databaseURL: 'https://{project}.firebaseio.com'
});
I also saw this question, creating new Google Cloud project from current Firebase project and upgrading Firebase project plan to Blaze Plan fixed the problem.

Related

Expo: cannot get getDevicePushTokenAsync due to non-valid Firebase project ID (Android)

I just started implementing push notifications in Expo - following the guides on expo.io. Hence, I created an Android app in my Firebase console and my app.json contains now a reference to the Google service file:
"android": {
"package": "------------",
"googleServicesFile": "./google-services.json",
"useNextNotificationsApi": true,
}
If I test this on a real android device (standalone app) I do not receive a valid token via this function:
token = (await Notifications.getExpoPushTokenAsync()).data;
Instead I get the following error:
Error: Encountered an exception while calling native method: Exception
occured while executing exported method getDevicePushTokenAsync on
module ExpoPushTokenManager: Please set your project ID. A valid
Firebase project ID is required to communicate with Firebase server
APIs: It identifies your project with Google."
I guess it has something to do with the way of my project setup. I also followed the Expo guides to setup firebase (e.g. for phone authentication) and hence created a web app in the Firebase console. In my application I initialize the Firebase web app with my web app configuration like this:
const FIREBASE_CONFIG: IFirebaseOptions = {
apiKey: '--------',
authDomain: --------.firebaseapp.com',
databaseURL: 'https://--------.firebaseio.com',
projectId: '--------',
storageBucket: '--------.appspot.com',
messagingSenderId: '--------',
appId: '--------',
measurementId: '',
trackingId: '',
};
firebase.initializeApp(FIREBASE_CONFIG);
The FIREBASE_CONFIG (for my Firebase Web App) as well as the google-services.json (for my Firebase Android App) have the correct project ID. Do I need to initialize the Firebase Android App somehow?
I am using Expo SDK 40.0.1.
What helped me: I deleted the old Firebase Android App, created a new one, downloaded the google-services.json file and built a new version of my app: It worked.
I cannot come up with an explanation why the first Firebase Android App was faulty because I did not make anything different than I did now.
Hopefully that will help some of you as well.
Hey I got this same issue with my react native project. Actually it was working fine but one day this error popped up so I checked the last working version of my files.
The actual issue was with the version of my google services in the gradle file.
Instead on 3.0.0, I have changed it to "classpath 'com.google.gms:google-services:4.3.8'".

'auth/invalid-api-key' When Letting the Admin SDK discover a service account

In different pages of the Firebase Admin SDK documentation, e.g., this page, it is suggested that:
If your code is deployed in an environment managed by Google, the
Admin SDK can attempt to auto-discover... the service account
provisioned for your app...To make use of these signing methods,
initialize the SDK with Google Application Default credentials and do
not specify a service account ID string: admin.initializeApp();
When I do this, I get the following error message:
[Error: Your API key is invalid, please check you have copied it
correctly.] code: 'auth/invalid-api-key', message: 'Your API key
is invalid, please check you have copied it correctly.'
Note that I do not get this error message when I manually download and import the credentials and service account JSON files in my project.
Detailed information for reproduction of the error:
1- I'm deploying this on Cloud Functions using Firebase CLI. So, basically, I use firebase deploy.
2- Here is the minimal code in my Node.js App:
const admin = require("firebase-admin");
const config = require("./firebase-config");
admin.initializeApp();
const firebase = require("firebase");
firebase.initializeApp(config);
const functions = require("firebase-functions");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const cors = require("cors");
app.use(cors());
app.get("/", Some_Function);
exports.api = functions.https.onRequest(app);
The error happens when I replace firebase.initializeApp(config); with firebase.initializeApp();
You're trying to initialize the Firebase Client SDK in a server-side environment:
const firebase = require("firebase");
firebase.initializeApp(config);
The client SDK accepts a whole different set of credentials compared to firebase-admin. You can initialize firebase-admin without any arguments in GCP managed environments (e.g. Cloud Functions, Cloud Run), but the same doesn't apply to firebase. You need to provide a valid client app configuration obtained from your Firebase project.
const admin = require('firebase-admin');
admin.initializeApp(); // This is ok
const firebase = require('firebase');
firebase.initializeApp(); // This is wrong
See https://firebase.google.com/docs/web/setup#config-object for details on how to obtain a client app configuration.
Also please note that using the client SDK in an environment like Functions is rather unusual. I'd advise you rethink your use case, and see if you really need to use firebase client SDK in your function.
I have tried
dotenv did not work
process.env.PRIVATE_KEY.replace(/\\n/g, '\n') did not work
Step1: go to the console and generate new service account file
Step2: export GOOGLE_APPLICATION_CREDENTIALS='path/to/serviceAccount.json'
(it doesn't matter where it is, e.g : 'user/username/download/serviceAccount.json')
Step3: if(!admin.apps.length) admin.initializeApp(); In the docs, either export the json object as param or no param with step 2

why is firebase serve throwing error but not firebase deploy?

I am new to firebase. I tried connecting firestore and cloud functions(Node JS).
I tried running firebase serve
but it showed an error saying there's a problem with unable to load the default credential in gcloud.
I already tried firebase deploy which works completely fine. It shows error only when I run locally.
Do I need to create an account in google cloud too and link my app to it?
Here's the full output error:
i functions: Beginning execution of "getScreamDet"
> Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
> at GoogleAuth.getApplicationDefaultAsync (/Users/vigneshwar/Desktop/rsocialapp-backend/functions/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
> at process._tickCallback (internal/process/next_tick.js:68:7)
I suppose you are trying to use firebase-admin package.
As for the latest firebase-admin, you cannot init with default credential like this.
const admin = require('firebase-admin');
admin.initializeApp();
You would need to use a serviceAccount credential. Go to Firebase Project Settings > Service Accounts > FirebaseAdminSdk. Copy the code for initialization.
You would end up with something similar to this:
const admin = require('firebase-admin');
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "xxxxx"
});

How do you best manage database URL in firebase cloud functions?

I have a dev database and a staging database and I want my firebase cloud functions to use whichever database is appropriate based on where it is deployed, is there a variable or something that I can reference for this so that I dont have to manually change the URL before every deploy to dev or staging environment?
var FirebaseDBUrlVar = 'some-url-to-firebase-dev';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: FirebaseDBUrlVar,
});
Starting version version 1.0 of the firebase-functions SDK, you can initialize the SDK with no arguments, and it will automatically pick up all the defaults for your environment:
admin.initializeApp()
If you need to add a service account to that, you can parse the defaults out of process.env.FIREBASE_CONFIG and add the credential to it:
const serviceAccount = require('./service-account-credentials.json')
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG)
adminConfig.credential = admin.credential.cert(serviceAccount)
admin.initializeApp(adminConfig)

Firebase Admin SDK - Require is not defined

I'm currently looking through the Firebase documentation found here...
https://firebase.google.com/docs/admin/setup
... regarding how to initialise the Admin SDK.
I know the article states adding the Firebase Admin SDK to your SERVER - but how would I add this to my application as I am unsure how to add it to a server.
I have tried simply adding it to my index.js file but the console returns the
`Uncaught ReferenceError: require is not defined`
My code:
var admin = require("firebase-admin");
var serviceAccount = require("/Users/morgannwg/Downloads/<JSON NAME>.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<URL>.firebaseio.com"
});
Any ideas?
Many thanks,
G
You need to create Node.js server app. Here's an example: https://github.com/firebase/quickstart-nodejs

Resources