firebase-tools getaddrinfo ENOTFOUND metadata.google.internal - javascript

I'm getting this error in my terminal:
#firebase/database: FIREBASE WARNING: {"code":"app/invalid-
credential","message":"Credential implementation provided to .
initializeApp() via the \"credential\" property failed to fetch a valid
Google OAuth2 access token with the following error: \"Failed to parse
access token response: Error: Error while making request: getaddrinfo
ENOTFOUND metadata.google.internal metadata.google.internal:80. Error
code: ENOTFOUND\"."}`
when using firebase-tools. This is the simple node script I'm trying to run.
const admin = require("firebase-admin");
const firebase = admin.initializeApp({
apiKey: "MY_API_KEY",
authDomain: "APP_ID.firebaseapp.com",
databaseURL: `https://DATABASE_URL.firebaseio.com`,
projectId: "APP_ID"
});
const snap = firebase
.database()
.ref("REF")
.child("ID")
.once("value");
console.log(snap);
Firebase tools version: 5.0.1
I've tried uninstalling and reinstalling, logging in and out of firebase-tools with firebase login / firebase-logout

the configuration has the wrong structure and lacks fields ...
admin.initializeApp({
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com',
credential: admin.credential.cert({
projectId: '<PROJECT_ID>',
clientEmail: 'foo#<PROJECT_ID>.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
})
});
you cannot just use the "web" configuration to access the Firebase Admin SDK.
because if this would be possible, the private key would be exposed to the public.
see the documentation.

I solved it simply by running :
firebase login
I also have this error when I don't have an internet connection.

Related

Error on Heroku when trying to post data ( error:0909006C Pem routines..._

I am trying to make a small nodeJS server deployed on Heroku, saving data to Firestore database. The server is deployed and running correctly.
I use Insomnia to test my requests and when I use it locally I can send a post request and save my data object to the database without issues. However, when I try to send a post request to Heroku, I get a 500 error with this message:
{ "code": 16, "details": "Failed to retrieve auth metadata with
error: error:0909006C:PEM routines:get_name:no start line",
"metadata": {}, "note": "Exception occurred in retry method that was
not classified as transient" }
I have read that it is necessary to add real line breaks in the env variable but I guess I am doing it already. This is my initializeApp function:
admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.PROJECT_ID,
privateKey: process.env.PRIVATE_KEY
? process.env.PRIVATE_KEY.replace(/\\n/gm, "\n")
: undefined,
clientEmail: process.env.CLIENT_EMAIL
}),
databaseURL: "XXXXX"
});
Any idea how to fix this?
I solved it by copy-pasting the key with break lines directly into Heroku config variables and removing .replace(/\\n/gm, "\n") from the code.
privateKey: process.env.PRIVATE_KEY
? process.env.PRIVATE_KEY
: undefined

Firebase Storage in Web Application: storage.useEmulator is not a function

In my local web application development environment the web application is accessing the Firestore emulator correctly, but not the Storage emulator. Instead it accesses the production storage.
I load the module from http://localhost:5000/__/firebase/8.3.0/firebase-storage.js
I have tried this from https://firebase.google.com/docs/emulator-suite/connect_storage#web-v8:
var storage = firebase.storage();
storage.useEmulator("localhost", 9199);
But the useEmulator function does not exist. How can this be?
The function storage.useEmulator was introduced in a later version of firebase.
Have you configured your connection before opening it?
var firebaseConfig = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket-url>'
};
firebase.initializeApp(firebaseConfig);
And, I don't have direct xperience about it, but have you tried this way?
firebase.storage.useEmulator('localhost', xxxx)
And beware this could be a work in progress stuff: try this cmd:
firebase --open-sesame storageemulator

firebase-messaging.js not found laravel

Hello everyone I am making an application using firebase for push notifications. This is my first project in firebase. The issue I am having is with the connection as when I run the project and click on the login button it gives me
Notification permission granted
But after this it returns an error which is as follow.
A bad HTTP response code (404) was received when fetching the script.
firebase.js:24 Unable to get permission to notify. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:8000/firebase-cloud-messaging-push-scope') with script ('http://localhost:8000/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration).
at https://www.gstatic.com/firebasejs/7.5.2/firebase-messaging.js:1:44674
I don't know why it is happening as I can see my js file and all the code as well, here is my config files.
In my firebase-messaging-sw.js which is on root directory the code is
importScripts('https://www.gstatic.com/firebasejs/7.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.2/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': 'SenderID'
});
const messaging = firebase.messaging();
console.log(messaging);
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
And in my firebase.js file the code is as follow:
const firebaseConfig = {
apiKey: "API-KEY",
authDomain: "authDomain",
databaseURL: "DBURI",
projectId: "P-ID",
storageBucket: "SB",
messagingSenderId: "SenderID",
appId: "AppID",
measurementId: "MeasurementID"
};
firebase.initializeApp(firebaseConfig);
//------------------------------------------------------------------------------
const messaging = firebase.messaging();
messaging.requestPermission().then(function () {
console.log("Notification permission granted");
return messaging.getToken();
}).then(function (token) {
console.log(token);
}).catch(function (err) {
console.log("Unable to get permission to notify.", err);
});
//------------------------------------------------------------------------------
messaging.onMessage((payload) => {
console.log(payload);
})
Any help would be appreciated. Thank you in advance.
I found the solution and it's working perfectly fine. Posting it for others who faces similar problem. The issue was in my firebase-messaging-sw.js file. I was initializing the firebase with sender id it was written in the documentation. I just initialized the firebase object with all the configuration values changing the initializing object solved my problem.

Firebase Admin With Credential

After coding some of my firebase functions, I deployed and got the following error:
Unexpected error while acquiring application default credentials: Could not load the default credentials.
I researched this error and came to the conclusion that this post would solve my issue: Firebase Cloud Functions: Error: Unexpected error while acquiring application default credentials: read ECONNRESET
I tried this solution. I downloaded a new private key to my desktop and then inserted the following code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var serviceAccount = require('/Users/nikhilsridhar/Desktop/test-eed0a-firebase-adminsdk-c4tmt-5d905a082b.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://test-eed0a.firebaseio.com"
});
However this does not solve my problem, but rather gives me a new error:
Error: Cannot find module '/Users/nikhilsridhar/Desktop/test-eed0a-firebase-adminsdk-c4tmt-5d905a082b.json'
What am I doing wrong?
So after some time I figured out that the service account file must be within the functions folder. Then make the path relative or in my example: ./test-eed0a-firebase-adminsdk-c4tmt-5d905a082b.json. This should work.
The function admin.credential.cert() receives a string parameter with the path of the firebase json key, this code works well for me with the auth method, you should add databaseURL and call .firestore() instead of auth():
import admin from 'firebase-admin'
export default admin.initializeApp({
credential: admin.credential.cert('../../firebase-key.json')
}).auth()
Watch what TypeScript says about that method:
cert(serviceAccountPathOrObject: string | admin.ServiceAccount, httpAgent?: Agent | undefined): Credential
Optional | HTTP Agentto be used when retrieving access tokens from Google token servers.
The path to a service account key JSON file or an object representing a service account key.
See | Initialize the SDK for more details.
#example
// Providing a path to a service account key JSON file
const serviceAccount = require("path/to/serviceAccountKey.json");
initializeApp({
credential: cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
#example
// Providing a service account object inline
initializeApp({
credential: cert({
projectId: "<PROJECT_ID>",
clientEmail: "foo#<PROJECT_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n"
}),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
#returns
A credential authenticated via the provided service account that can be used to initialize an app.

upload file on firebase web using node js throws error firebase.storage is not a function

i created a web app using node js express and firebase. i created a form which will upload a file to firebase but when i tried what's on the guide it gives an error..
var firebase = require('firebase');
var config = {
apiKey: "----------------------------------",
authDomain: "----------------------------------",
databaseURL: "-",----------------------------------
projectId: "---------",
storageBucket: "----------------",
messagingSenderId: "---------------"
};
firebase.initializeApp(config);
module.exports = firebase;
// Get a reference to the storage service, which is used to create references in your storage bucket
var storage = firebase.storage();
// Create a storage reference from our storage service
var storageRef = storage.ref();
this is the set up i use for using firebase on node js.
var storage = firebase.storage();
^
TypeError: firebase.storage is not a function
and this is the error i receive from the console. after searching they said that i need to use google-cloud npm. so my question is if i install google-cloud on my node do i need to create an account on google cloud platform?..
Node js google-cloud package is used instead of firebase to store files, videos etc. Right now firebase storage is not compatible with Nodejs that's why you are getting that error^, yoou can do something like this to use google-cloud:-
npm install --save google-cloud
And then to use storage in your project this is a sample code:-
const gcloud = require('google-cloud');
const storage = gcloud.storage({
projectId: //project id here,
keyFilename: //service account credentials here,
});
const storagebucket = storage.bucket('projectID.appspot.com');
This link here has the complete guide how to do google-cloud stuff.
https://medium.com/#stardusteric/nodejs-with-firebase-storage-c6ddcf131ceb

Categories