WebConfig doesn't return measurementId - firebase

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.

Related

Fetching from Firestore URL shows 404 - URL not right?

I am using Next.js to fetch data from my Firestore Database, but I keep getting an error in the console, stating that GET (FirestoreDatabaseURL) 404 (not found).
When I try any other json database such as myfakestore or jsonplaceholder, my code works (I tried both getServerSideProps and fetching with UseState), works beautifully. But not from my own database. Tried with Postman, but it won't work either.
I have tried to find different ways to get the database URL, but I am only finding this one format:
https://PROJECTID.firebaseio.com
The server is in us-central, which also helps determine the URL.
While testing around, I have gotten the error FetchError: invalid json response body at https://PROJECTID.firebaseio.com/ reason: Unexpected token F in JSON at position 0
Which I came to find out that it's not actually returning json, but HTML.
Just for context, this is my working code:
const [showProducts, setShowProducts] = useState()
const apiData = 'https://celeste-73695.firebaseio.com/'
let displayProducts
function pullJson () {
fetch(apiData)
.then(response => response.json())
.then(responseData => {
displayProducts = responseData.map(function(product){
return (
<p key={product.id}>{product.title}</p>
)
})
console.log(responseData)
setShowProducts(displayProducts)
})
//return
}
useEffect(() => {
pullJson()
},[])
And my firebase.js file
import firebase from 'firebase';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
export default db;
Can anybody point me in the right direction?
Thanks in advance.
The databaseURL property is for the Firebase Realtime Database, which you probably didn't create yet. The databaseURL property is not necessary to use Firestore though, so you should be able to access that with just the configuration data you have.
You may have created the realtime database but not have configured it with firebase config. I recommend you to go through this documentations for the realtime database.
To configure the firebase firestore you need to do the following:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
And make sure to export the db reference as will be used in your project.
After that you can start using the firestore like documented here as you have tried to use it with URL you may have to change the implementation for using it like shown in above documentations

How to use process.env on apollo-client? [duplicate]

I've been poking around with this for at least an hour and so far I'm stumped. Perhaps I'm not understanding the docs or the medium articles. But, as I understand it NextJS (I have have the latest version installed) provides a built in env variable solution. So, there is no need for the dotenv package.
Since NextJS is setup all I would need to do is create an env.local to store my API_KEY and other sensitive information. Then, once I save that updated file, I should be able to access ${process.env.API_KEY} and have access to that value anywhere in my code.
Provided the above statements are true, I'm not able to get that to work.
In my case I'm using environmental variables to connect to Firebase. In the code below it's being implemented. I get a 500 malformed error:
Connection GRPC stream error. Code: 3 Message: 3 INVALID_ARGUMENT:
Project id parakeat-a1-7706, is malformed: it either contains invalid
characters or is too long. Look at https://cloud.google.com
/resource-manager/docs/creating-managing-projects#identifying_projects
for instructions in how to get a project's id.
import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';
import 'firebase/analytics';
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
};
// Initialize Firebase
try {
firebase.initializeApp(config);
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack);
}
}
// const firebaseAnalytics = firebase.analytics();
const firebaseStorage = firebase.storage();
const firebaseFirestore = firebase.firestore();
export { firebaseStorage, firebaseFirestore };
The ID is correct shown above, so what's wrong? Why is it that if I put the actual value directly in and skip the process.env it successfully connects?
By default all environment variables loaded through .env.local are only available in the Node.js environment (in methods like getStaticProps), meaning they won't be exposed to the browser.
In order to expose a variable to the browser, you have to prefix the variable with NEXT_PUBLIC_. For example:
NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
Docs
I have used the above solution before but later on needed to include my .env variables in the bundle which is why I used the next.config.js file to house my variables.
Check this link to their documentation for reference:
Nextjs - next.config.js

'Firebase' connection problem, Same code worked in 'react JS' but not worked in 'react native' projects?

firebase-config.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "**********************************",
authDomain: "***********.firebaseapp.com",
projectId: "***********",
storageBucket: "***********.appspot.com",
messagingSenderId: "*************",
appId: "******************************",
measurementId: "****************",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };
package.json
{
"firebase": "^9.4.0", // latest version
}
It gives this error when running the app
ERROR [2021-11-16T08:33:02.823Z] #firebase/firestore: Firestore (9.4.0): Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
How to solve this error?
For react native.
Consider [https://rnfirebase.io/]. This will help you how to install Firebase in react native. As React Native is a cross platform and runs on native dom therefore you need to link the libraries and also add your bundle and package id in firebase console.
Again DONT WORRY, this link will help you to do everything easily.

Expo and firebase cloud functions

Edit:
I Solved the Problem by changing import '#firebase/functions' to import 'firebase/functions'
I'm creating an app using expo and firebase.
I trying to add Cloud functions to be callable in my app.
My code is the following in my FirebaseApi.js
import * as firebase from 'firebase'
import '#firebase/functions'
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
}
export default class Firebase {
static auth;
static database;
static storage;
static functions;
static EmailAuthProvider;
static init() {
firebase.initializeApp(firebaseConfig);
Firebase.auth = firebase.auth();
Firebase.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
Firebase.EmailAuthProvider = firebase.auth.EmailAuthProvider;
Firebase.database = firebase.database();
Firebase.storage = firebase.storage();
Firebase.functions = firebase.functions();
}
}
First i encountered the error that firebase.functions() is undefiend, which lead me to the following article on here: Implement callable cloud functions in Firebase client app
But this solution doesn't seem to work with firebase.
I did call npm install --save #firebase/functions and in my package.js #firebase/functions is insalled.
But when trying to build the app it states
Unable to resolve #firebase/functions" from ".//js/firebase/firebaseAPI.js"
Am i doing something wrong, or is there maybe a problem using Firebase Cloud functions with expo?
The solution in the link was almost right.
For me, I needed to ditch the #.
So, instead of
import '#firebase/functions'
you need
import 'firebase/functions'

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