A learner in React native and Firebase.
Here is my code to intialize firebase storage and fetch url for a storage path:
import { firebase } from '#react-native-firebase/storage';
var firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const storage = firebase.storage();
let imageRef = firebase.storage().ref('photos/flower.png');
console.log(imageRef);
I expect imageRef to be containing url for the Firebase storage's image file.
But I get the error:
ERROR TypeError: undefined is not an object (evaluating
'_firebase.firebase.storage')
I feel, the error is due to wrong package name import.
Could someone guide me on what is wrong?
I expect imageRef to be containing url for the Firebase storage's image file.
Firstly, you should follow the example in the documentation.
The core documentation also says:
Unlike the Firebase Web SDK, there is no need to manually call the initializeApp method with your project credentials.
So you shouldn't have to call initializeApp at all if you set things up correctly.
ref() returns a Reference type object, which is just a pointer to the file. If you want an HTTPS type URL to download the content of that file, you will need to use its getDownloadURL method to get that.
import storage from '#react-native-firebase/storage';
let imageRef = storage().ref('photos/flower.png');
imageRef.getDownloadURL().then(url => {
console.log(url);
})
Related
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 deployed a React app, but I'm receiving the error message:
#firebase/database: FIREBASE FATAL ERROR: Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp().
How do I fix this issue?
My firebase.js file currently looks like this...
import firebase from "firebase";
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
});
const database = firebase.database();
export const auth = firebase.auth();
export default database;
My .env.local file looks like this (I redacted full details)
REACT_APP_FIREBASE_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXmRv4
REACT_APP_FIREBASE_AUTH_DOMAIN=XXXXXXXXXXXXXXXXXXXXXXXXXd99c.firebaseapp.com
REACT_APP_FIREBASE_PROJECT_ID=XXXXXXXXXXXXXXXXXXXXXXXXXproject-fd99c
REACT_APP_FIREBASE_STORAGE_BUCKET=XXXXXXXXXXXXXXXXXXXXXXXXXd99c.appspot.com
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=XXXXXXXXXXXXXXXXXXXXXXXXX706
REACT_APP_FIREBASE_APP_ID=XXXXXXXXXXXXXXXXXXXXXXXXX54da93
Your configuration object (the one you pass to initializeApp) is missing a databaseURL property. It's unclear from your question why it's missing or what you may have done to omit it, but that's what you need. You can get the string value for that property in the Firebase console for your app under "project settings".
I'm making an app that writes a waiting list in the firebase realtime databse, but when I try to run this simple bit of code, I get this error (Note- I'm running this on web):
class FirebaseMethods {
FirebaseDatabase database = FirebaseDatabase.instance;
void createPartyWaiting(String partyCode, String partyHostName) async {
partyCode = partyCode.trim();
DataSnapshot data = await database.ref("e").get();
print(data.value);
}
}
and i'm calling it as-
await FirebaseMethods().createPartyWaiting("PartyCode123", "Adam");
But when I call it, I get this error-
Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com
at Re (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:22344)
at Ws (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:148180)
at au (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:166314)
at K.xu.INTERNAL.registerComponent.Y.setServiceProps.Reference [as instanceFactory] (https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js:1:187315)
I'm initializing the web like this (I've censored the actual values)-
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (kIsWeb) {
Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "apikey",
authDomain: "authDomain",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"));
}
runApp(const MyApp());
}
I've also found out that there's this optional arguement to the initilaziation method-
But after adding my databaseUrl here, I got this error-
Error: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
at Object.throw_ [as throw] (http://localhost:53659/dart_sdk.js:5063:11)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:53659/packages/firebase_core_web/firebase_core_web.dart.lib.js:248:27)
What am I doing wrong, and how do I fix this? Thanks!
For anyone who has used $ flutterfire configure to configure firebase to your flutter project as shown in here before adding Realtime Database, you will have to run the command again to reconfigure your project or add "databaseURL" to the FirebaseOptions in your lib/firebase_options.dart.
Your lib/firebase_options.dart should look something like this:
// inside lib/firebase_options.dart
// ...
static const FirebaseOptions web = FirebaseOptions(
apiKey: '...',
appId: '...',
messagingSenderId: '...',
projectId: 'project-id',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://your-database-id.firebasedatabase.app', // IMPORTANT!
storageBucket: 'project-id.appspot.com',
measurementId: '...',
);
// ...
Since you're configuring your Firebase project (for web) by passing the configuration data to Firebase.initializeApp, you should also include the URL for your database there:
Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "apikey",
authDomain: "authDomain",
databaseURL: "the URL for your database", // 👈
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"));
You can find this URL in your browser by going to the Realtime Database panel in the Firebase console:
I'm not sure why the databaseURL doesn't show in your auto-complete though, as I have it in all of my Dart configs (most of which are generated by the FlutterFire CLI).
If entering the databaseURL manually gives an error message, I recommend checking if you're on the latest version of the libraries (although I don't recall this ever not being present).
I recreated the flutter and firebase project with a new app id, and it worked.
I have been trying to develop a fully functional, reusable firebase authentication app however after looking online at multiple different solutions, I have developed the below which works perfectly but from my understanding there is no way to protect the API keys/sensitive data? Is there anyway to use environment variables on the plugins/firebase.js file?
The nuxt/firebase docs suggests declaring them within the nuxt.config.js file? But when following the docs and trying to install firebase & #nuxtjs/firebase I keep running into errors. NPM error when I am trying to install #nuxtjs/firebase
Is there any definitive/working best practise to follow when working with Nuxt & Firebase?
~plugins/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore'
import 'firebase/storage'
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
export const auth = firebase.auth()
export const google = new firebase.auth.GoogleAuthProvider()
export const storage = firebase.storage()
export default firebase
~/plugins/fireauth.js
import { auth } from '~/plugins/firebase.js'
export default (context) => {
const { store } = context
return new Promise((resolve, reject) => {
auth.onAuthStateChanged(user => {
console.log(user);
store.dispatch('setUser', user)
resolve(user)
}, err => {
reject(err)
})
})
}
Update to #Kissu
The environment variables are now working as per #kissu's comments below - however the app is now crashing because the initializeApp() is not being run.
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
~/plugins/firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
import 'firebase/compat/storage'
export default ({ $config }) => {
const firebaseConfig = {
apiKey: $config.firebaseConfig.apiKey,
authDomain: $config.firebaseConfig.authDomain,
projectId: $config.firebaseConfig.projectId,
storageBucket: $config.firebaseConfig.storageBucket,
messagingSenderId: $config.firebaseConfig.messagingSenderId,
appId: $config.firebaseConfig.appId
}
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
}
export const auth = firebase.auth()
export const google = new firebase.auth.GoogleAuthProvider()
export const storage = firebase.storage()
Resources:
https://firebase.nuxtjs.org/
https://dev.to/drewclem/building-user-accounts-with-nuxt-vuex-and-firebase-2o6l
In your Firebase Config, you can use local environment variables (from your .env file) using process.env.VUE_APP_:
// ~/plugins/firebase.js
const firebaseConfig = {
apiKey: process.env.VUE_APP_FIREBASE_apiKey,
authDomain: process.env.VUE_APP_FIREBASE_authDomain,
projectId: process.env.VUE_APP_FIREBASE_projectId,
storageBucket: process.env.VUE_APP_FIREBASE_storageBucket,
messagingSenderId: process.env.VUE_APP_FIREBASE_messagingSenderId,
appId: process.env.VUE_APP_FIREBASE_appId,
measurementId: process.env.VUE_APP_FIREBASE_measurementd,
};
But be sure to set your Variables in your .env file like this:
// ~/.env
// NOTE: THIS FILE IS NOT COMMITTED TO CODE REPOSITORY / GITHUB AND SHOULD BE IGNORED BY DEFAULT IN YOUR `.gitignore` FILE
// NOTE: For Vue.js environment variables, you must prefix them with `VUE_APP_`
VUE_APP_FIREBASE_apiKey=
VUE_APP_FIREBASE_authDomain=
VUE_APP_FIREBASE_projectId=
VUE_APP_FIREBASE_storageBucket=
VUE_APP_FIREBASE_messagingSenderId=
VUE_APP_FIREBASE_appId=
VUE_APP_FIREBASE_measurementId=
Where after the = you put your secret keys and ID's. NOTE: Be sure to leave NO SPACE between the = and your key. For example:
VUE_APP_FIREBASE_apiKey=YOUR.KEY.HERE
...
You can read more documentation on VUE_APP Environment Variables here: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
This .env file should not be committed to Github, or your code repository. Instead, set these variables on your production environment. For example, if you are using Netlify or Heroku, you will want to set Environment Variables with the EXACT same names like VUE_APP_FIREBASE_apiKey and set its value to be equal to your Key.
If using Netlify, set your Environment Variables in your Build & Deploy Site Settings:
https://app.netlify.com/sites/{{YOUR_SITE_HERE}}/settings/deploys#environment
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'