why is firebase serve throwing error but not firebase deploy? - firebase

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"
});

Related

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

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.

FirebaseError: Missing or insufficient permissions after deleting Google Service Accounts

Use Case
I am using Firebase JS SDK to access Cloud Firestore from Browser, so that I can push UI Logs and Errors into Firestore.
Issue
It was all working fine until I, accidentally, deleted most of the Service Accounts in my Google Cloud Platform inside APIs & Services → Credentials.
Below is the sample Config that we use for a Firebase Web App:
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCztfcT6k6yXXXXXXXXXXXXXXXXXX",
authDomain: "<some-domain>.firebaseapp.com",
databaseURL: "https://<some-domain>.firebaseio.com",
projectId: "<some-domain>",
storageBucket: "<some-domain>.appspot.com",
messagingSenderId: "877458876543",
appId: "1:877458876543:web:9a9287dee234cd655ab7f2"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
I even tried reading Firebase Service Accounts Overview, but could not decide which Service Account to use for Firestore. Then, I tried adding different Service Accounts according to my Project ID and giving them Owner permissions to my Project, but it didn't work.
Full Error I am getting in Browser's Console:
Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
at new Hr (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:48219)
at https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:378673
at wr.<anonymous> (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:377569)
at Wt (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:15221)
at wr.S.dispatchEvent (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:16063)
at Er.ua (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:45322)
at nr.S.Fa (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:43229)
at Ge (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:21453)
at qe (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:20854)
at Me.S.Ja (https://www.gstatic.com/firebasejs/7.8.2/firebase-firestore.js:1:23264)
Actually, I want to cleanup my Service Accounts as there were many created by myself. Please guide in telling which Service Account to use and what suitable Permissions to give.
Firestore Security Rules depend on a service account named service-PROJECT_NUMBER#firebase-rules.iam.gserviceaccount.com with the role
roles/firebaserules.system. You can use gcloud to restore this account:
gcloud projects add-iam-policy-binding PROJECT_ID --member=serviceAccount:service-PROJECT_NUMBER#firebase-rules.iam.gserviceaccount.com --role=roles/firebaserules.system
To get the project number, see Identifying projects.

'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

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