Firebase 3.0 failed initializeApp - firebase

Migrating to firebase 3.0 but it's failed to initialize.
var firebase = require('firebase');
// Initialize Firebase
var config = {
apiKey: "key",
authDomain: ".firebaseapp.com",
databaseURL: ".firebaseio.com",
storageBucket: ".appspot.com",
};
firebase.initializeApp(config);
module.exports ={
return : {
auth : firebase.auth,
database : firebase.database(),
storage : firebase.storage()
}
}
node_modules\firebase\auth-node\auth.js:61
throw new Error('Invalid service account provided');
at \node_modules\firebase\auth-node\index.js:31:9
at \node_modules\firebase\app-node.js:11:272
installed firebase : 3.0.2,
node : 4.4.2
"express": "^4.13.4"

Try to copy the correct setup settings from the Web Setup tab with the relevant APIkeys.

Try to delete the [DEFAULT] app and reinitialize. I think the code is somthing like
firebase.app.delete().then(function(){
)};

I faced the same issue. Check it here: Firebase "throw new Error('Invalid service account provided');" error message.
You need to create a service account and add it to your firebase app configuration.
firebase.initializeApp({
serviceAccount: "path/to/serviceAccountCredentials.json",
databaseURL: "https://databaseName.firebaseio.com"
})

Related

WebConfig doesn't return measurementId

I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.

I can't authenticate Firebase with correct details. Get error: Make sure to initialize the SDK with a service account credential

I have followed these instructions and copied my Firebase config details, yet I keep getting told it can't be authenticated. I have tried both service account json file and ID. No idea why I get error because the Firebase details are correct.
Setup:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import { attachCustomCommands } from 'cypress-firebase';
// import * as serviceAccount from '../support/serviceAccountKey.json'
const fbConfig = {
// Your config from Firebase Console
apiKey: "",
authDomain: ".firebaseapp.com",
// credential: serviceAccount,
databaseURL: "firebaseio.com",
projectId: "test-dev",
serviceAccountId: 'cypress#test-dev.iam.gserviceaccount.com',
storageBucket: "test-dev.appspot.com",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(fbConfig);
attachCustomCommands({ Cypress, cy, firebase });
Login:
before(() => {
cy.clearFirebaseAuth()
// cy.visit(Cypress.env("baseUrl"))
// cy.completeLoginScreen(Cypress.env("standardUserEmail"), Cypress.env("standardUserPassword"))
// cy.verifyLogin()
cy.request('POST', Cypress.env("baseUrlApi") + "auth", {
email: Cypress.env("standardUserEmail"),
password: Cypress.env("standardUserPassword"),
}).then((response) => {
cy.login(response.body.uid)
// cy.setCookie('token', response.body.token)
// window.localStorage.setItem("token", response.body.token)
// window.localStorage.setItem(response.body.token, response.body.uid);
})
})
Error message:
cy.task('createCustomToken') failed with the following error:
> Failed to determine service account. Make sure to initialize the SDK with a service account credential.
I got it working by posting in cypress config file instead:
export default defineConfig({
e2e: {
async setupNodeEvents(on, config) {
cypressFirebasePlugin(on, config, admin, {
credential: admin.credential.cert(serviceAccount as admin.ServiceAccount)
});

Firebase App Check with Vue 3 Invalid app resource name

I am trying to get Firebase App Check working in a Vue 3 web app. I have Firebase configured and reCAPTCHA v3 configured.
Here is the code where I initialize Firebase and App Check. I am logging the recaptcha site key to console to make sure the env variables are getting injected correctly.
const fbConfig = {
apiKey: import.meta.env.VITE_APP_FIREBASE_APIKEY,
authDomain: import.meta.env.VITE_APP_FIREBASE_AUTHDOMAIN,
projectId: import.meta.env.VITE_APP_FIREBASE_PROJECTID,
appId: import.meta.env.VITE_APP_FIREBASE_APPID,
storageBucket: import.meta.env.VITE_APP_STORAGEBUCKET,
messagingSenderId: import.meta.env.VITE_APP_MESSAGINGSENDERID,
}
const fbapp = initializeApp(fbConfig)
if (location.hostname === "localhost") {
self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
}
console.log("APPCHECK Token: ", import.meta.env.VITE_APP_RECAPTCHA_SITEKEY)
const appCheck = initializeAppCheck(fbapp, {
provider: new ReCaptchaV3Provider(import.meta.env.VITE_APP_RECAPTCHA_SITEKEY),
// Optional argument. If true, the SDK automatically refreshes App Check
// tokens as needed.
isTokenAutoRefreshEnabled: true
});
This works as expected on local host where the debug token is used. When I deploy to a live site I get this error.
{ code: 400, message: "Invalid app resource name: \"projects/<name removed>/apps/\"<code removed>\"\".", status: "INVALID_ARGUMENT" }
Any thoughts?
Found the problem. The appId was getting quoted in the environment variables for some reason. Fixing that fixed the issue.

Firebase: Update Firestore Fails If Document Does Not Exist [duplicate]

This is my very basic Cloud Function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore()
exports.createdNewAccount = functions.auth.user().onCreate(event => {
return db.collection('users').doc(event.data.uid).update({
"creationDate" : Date.now()
})
})
And I get the error
Error: no entity to update: app
What is wrong with my code?
Most likely, the document for event.data.uid does not exist. The documentation for update() states:
The update will fail if applied to a document that does not exist.
Use set() instead.
I faced a similar error when testing my app locally with the Firebase emulator. My firebase config file looked like:
import firebase from "firebase";
import "firebase/firestore";
const firebaseConfig = {
apiKey: <FIREBASE_API_KEY>,
authDomain: <FIREBASE_AUTH_DOMAIN>,
databaseURL: <FIREBASE_DB_URL>,
projectId: <FIREBASE_PROJECT_ID>,
storageBucket: <FIREBASE_STORAGE_BUCKET>,
messagingSenderId: <FIREBASE_MSG_SENDER_ID>,
appId: <FIREBASE_APP_ID>,
measurementId: <FIREBASE_MEASUREMENT_ID>,
};
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
// for local instances, use the emulator to connect the frontend to firestore & functions
if (location.hostname === "localhost") {
firebase.firestore().settings({
host: "localhost:8080",
ssl: false,
});
firebase.functions().useFunctionsEmulator("http://localhost:5001");
}
Turns out my local Firestore database (expected to be running at localhost:8080) wasn't being hit. So my cloud functions were trying to write to a non-existent db. The underlying issue was that I also had my backend initializing to a different database:
// functions/index.js
const admin = require("firebase-admin");
var serviceAccount = require("./serviceAccount.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://other-firebase-project-id.firebaseio.com",
});
The solution (originally adapted from a Fireship tutorial) was to remove this [incorrect] re-initialization of the database altogether:
// functions/index.js
...
admin.initializeApp();
...
After all, according to the docs, we can initialize the Firebase Admin SDK without parameters since the FIREBASE_CONFIG environment variable is included automatically in Cloud Functions for Firebase functions that are deployed via the Firebase CLI.
FWIW, also be sure to set the correct Firebase project on the CLI. Doing so with this allows the Firebase CLI to hook Functions/Firestore to the right project:
firebase use <desired-firebase-project-id>
If you have multiple Firebase projects, you can list them out with: firebase projects:list

Use firebase auto SDK setup with Webpack

I am creating a web app that uses Vue webpack with firebase. I would like to have my firebase credentials automatically change when i use firebase use <some_alias> on the firebase cli. In other projects, this simply meant including the /__/firebase/init.js file of firebase hosting. In this project, I am using the npm firebase library and can load in a specific firebase set of credentials with
import firebase from 'firebase'
var config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
firebase.initializeApp(config)
export default {
database: firebase.database,
storage: firebase.storage,
auth: firebase.auth
}
However, this does not get my credentials based on my current firebase workspace. Instead, I would like something like
import firebase from 'firebase'
const fbcli = require('firebase-tools');
export const getFirebaseInstance = () => {
return fbcli.setup.web().then(config => {
firebase.initializeApp(config)
return firebase
});
}
though synchronous. Is there any way to synchronously load in my firebase credentials?
This was solved by checking window.location.host when in the prod environment and having a production config object if the host was our production hostname and reading from the values of a configuration file otherwise.
Try using fs.writeFileSync as described in this example from a firebase blog post about reading credentials:
const fbcli = require('firebase-tools');
const fs = require('fs');
// by default, uses the current project and logged in user
fbcli.setup.web().then(config => {
fs.writeFileSync(
'build/initFirebase.js',
`firebase.initializeApp(${JSON.stringify(config)});`
);
});

Resources