I'm using my API key stored in a .env.local file. And it setup correctly but not working
assert.ts:128 Uncaught FirebaseError: Firebase: Error (auth/invalid-api-key).
at createErrorInternal (assert.ts:128:1)
at _assert (assert.ts:153:1)
at register.ts:67:1
at Component.instanceFactory (register.ts:90:1)
at Provider.getOrInitializeService (provider.ts:318:1)
at Provider.initialize (provider.ts:242:1)
at initializeAuth (initialize.ts:66:1)
at getAuth (index.ts:44:1)
at Module../src/firebase.init.js (firebase.init.js:22:1)
at Module.options.factory (react refresh:6:1)
I don't know why React is giving me an error. I intialized firebase in the following file
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
// 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: process.env.REACT_APP_apiKey,
authDomain: process.env.REACT_APP_authDomain,
projectId: process.env.REACT_APP_projectId,
storageBucket: process.env.REACT_APP_storageBucket,
messagingSenderId: process.env.REACT_APP_messagingSenderId,
appId: process.env.REACT_APP_appId,
measurementId:process.env.REACT_APP_measurementId
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export default auth;
It is likely that you are having multiple render of your app. Do it this way:
const firebaseConfig = {
apiKey: process.env.REACT_APP_apiKey || 'test',
authDomain: process.env.REACT_APP_authDomain || 'test',
projectId: process.env.REACT_APP_projectId || 'test',
storageBucket: process.env.REACT_APP_storageBucket || 'test',
messagingSenderId: process.env.REACT_APP_messagingSenderId || 'test',
appId: process.env.REACT_APP_appId || 'test',
measurementId:process.env.REACT_APP_measurementId || 'test'
};
In that case at the first render, when the environment variables are yet available, you will have default values, not null or undefined values.
I hope it helps someone.
Related
I have just set up my app and integrated appcheck
and the code looks like
import { initializeApp, getApps } from "firebase/app";
import { getAuth, } from "firebase/auth";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";
let app;
if (!getApps().length) {
app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
}
async function initialize() {
const { initializeApp } = require("firebase/app");
const { initializeAppCheck, ReCaptchaV3Provider } = require("firebase/app-check");
const app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
return initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(process.env.NEXT_PUBLIC_APP_CHECK_KEY),
isTokenAutoRefreshEnabled: true
});
}
if (typeof window !== "undefined") {
initialize().then((res)=>{
// console.log(res)
}).catch((err)=>{
throw(err)
})
}
export const auth = getAuth();
export const db = getFirestore();
export default app;
So when i set isTokenAutoRefreshEnabled to true, the error comes up and when I set it to false everything works.
I am using firebase ^9.9.4 and this gives the above error so I decided to downgrade and use firebase ^9.8.2 since I had set up a different project the same way and there were no errors. In this version, I get the error
FirebaseError: AppCheck: Fetch server returned an HTTP error status. HTTP status: 400. (appCheck/fetch-status-error).
at exchangeToken
What is this error and how can I fix it
yesterday my application had no problems when it wanted to request fcm tokens, suddenly now it can't, and the error that appears is:
error result
my assumption is because firebase-messaging-sw can't be active, it's not even in the build result folder, even though yesterday there was no problem at all. the firebase I'm using is version 9 so it's modular.
firebase-messaging-sw.js
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
apiKey: "--------",
authDomain: "-------",
projectId: "------",
storageBucket: "-----",
messagingSenderId: "------",
appId: "---------"
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);
main.js
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import { initializeApp } from "firebase/app";
import './utils/firebase-messaging-sw'
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: "---------------------",
authDomain: "-----------------------",
projectId: "---------------------",
storageBucket: "----------------------",
messagingSenderId: "-----------------------",
appId: "---------------------------"
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging();
getToken(messaging, { vapidKey: '---------------------------------' }).then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
createApp(App).use(store).use(router).mount('#app')
after build the firebase-messaging-sw.js file should also be in it, that's what happened yesterday, but somehow now suddenly it can't
build result
because i use pwa, there should be 2 active service workers
service worker from Vue
service worker from firebase-messaging-sw
in fact the only active ones are vue's service workers
active service workers
here is my directory structure
directory
I cannot read or write to the firebase real-time database... please help.
I have set my rules to both read and write 'true', and I've tested it in the playground.
I'm using the create-react-app boilerplate setup.
My version of the firebase is 9.6.4
Here's my firebase file
import { initializeApp } from 'firebase/app';
import { getDatabase, set, ref } from 'firebase/database';
const firebaseConfig = {
apiKey: 'AIzamGZ1LBAAtb',
authDomain: 'helpme.firebaseapp.com',
databaseURL: 'https://helpme.firebaseio.com',
projectId: 'helpme',
storageBucket: 'helpme.appt.com',
messagingSenderId: '93help1',
appId: '1:293268271119:web:d4e9e73help',
measurementId: 'helpKQLWS',
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
set(ref(db, 'chatroom'), {
name: '',
createdAt: '',
photo: '',
});
I am trying to get my datas from firebase with console log but i am getting an error.
The error is: image
This is my database: https://i.stack.imgur.com/A1zYm.png
<script type="module">
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import {
getDatabase,
set,
ref,
update
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
const firebaseConfig = {
apiKey: ,
authDomain: ,
databaseURL: ,
projectId: ,
storageBucket: ,
messagingSenderId: ,
appId: ,
measurementId:
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth();
const firebaseRef = firebase.database().ref("Users");
firebaseRef.once("value", function(snapshot) {
snapshot.forEach(function(element) {
console.log(element);
})
});
</script>
You're trying to use the old v8 syntax with Firebase SDK 9, which won't work. You'll either have to use the new modular syntax, or import the older SDKs or the compatibility versions on v9.
In v9 syntax, getting a reference to and reading a value from the database is done with:
import { getDatabase, ref, get } from "firebase/database";
...
const database = getDatabase();
const firebaseRef = ref(database, "Users");
get(firebaseRef, function(snapshot) {
snapshot.forEach(function(element) {
console.log(element);
})
});
For more examples, see the Web version 9 (modular) tabs in the documentation I linked above, and the upgrade guide specifically the section on upgrading with the compat libraries.
For the past week I've been trying to setup Firebase Cloud Functions, but have been unable to import the dependencies needed.
This is in my script.js file, my main code:
import firebase from "firebase/app"
require("firebase/functions");
const testFunction = httpsCallable(functions, 'testFunction')
That returns this error:
script.js:7 Uncaught ReferenceError: httpsCallable is not defined
at Object.parcelRequire.script.js.firebase/app (script.js:7)
at newRequire (script.75da7f30.js:47)
at script.75da7f30.js:81
at script.75da7f30.js:120
In my index.html, I have this:
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-functions.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-analytics.js"></script>
<script>
const firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXX-XXXXX.firebaseapp.com",
databaseURL: "https://XXXXX-XXXXX-default-rtdb.firebaseio.com",
projectId: "XXXXX-XXXXX",
storageBucket: "XXXXX-XXXXX.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXXXXX:web:XXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
firebase.analytics()
</script>
What am I missing?
Edit: To upgrade to the new version of Firebase, I removed the script references in my html, did "npm i firebase#9.1.3" in my project folder, moved everything to my script.js file, and this is what it looks like now. But I still get the httpsCallable is not defined error, so the version didn't seem to affect it.
import firebase from "firebase/compat/app"
import 'firebase/compat/functions'
import 'firebase/compat/auth'
import 'firebase/compat/analytics'
import 'firebase/compat/database'
const firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXX-XXXXX.firebaseapp.com",
databaseURL: "https://XXXXX-XXXXX-default-rtdb.firebaseio.com",
projectId: "XXXXX-XXXXX",
storageBucket: "XXXXX-XXXXX.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXXXXX:web:XXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
firebase.analytics()
When using the legacy namespaced syntax (<v8 & v9 compatibility-mode), use:
import firebase from "firebase/compat/app" // just firebase/app in <v8
import 'firebase/compat/functions' // just firebase/functions in <v8
const testFunction = firebase.functions().httpsCallable('testFunction')
testFunction({ /* data */ })
.then((result) => { /* ... */ })
.catch((err) => { /* ... */ })
For the modern modular syntax (v9+), use:
import { getFunctions, httpsCallable } from 'firebase/functions'
const testFunction = httpsCallable(getFunctions(), 'testFunction')
testFunction({ /* data */ })
.then((result) => { /* ... */ })
.catch((err) => { /* ... */ })
These are documented here.