Im getting the error 'Firebase: Error (auth/invalid-api-key) ' even though all my authentication values were correct.
Create a separate file called 'firebase.config.js'. In the file, only have an 'export const' variable with the credentials for the firebase. Here is my file:
export const firebaseConfig = {
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,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEAUREMENT_ID
};
Go back to 'firebase.js' file, remove credentials from there, then reference the recently created variable from file with this line
import { firebaseConfig } from './firebase.config';
Finally, Initialize the Firebase shown below
const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const db = getFirestore(app);
Related
I'm very new to next.js, and I'm developing an API with it, side that API I want to use firebase, so I set up firebase but when I try to call it, this error appears: "unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization"
Code below.
Firebase config file
import firebase from 'firebase/app';
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "*******",
authDomain: "********",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
//if(!firebase.apps.length){
//}
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
Firestore service
import { firestore } from './firebase';
export class Firestore {
async getOne(collection, uid){
const data = await firestore.collection(`${collection}/${uid}`).get();
return await data.docs();
}
}
API page
import {Firestore} from '../../utils/firestore';
const firestore = new Firestore();
const getBanners = () => {
return firestore.getOne('settings','client');
//return data;
}
export default function Handler(req,res){
res.status(200).json({
'name':"getBanners",
'data': getBanners()
});
}
I solved this issue by adding import firebase from 'firebase/compat/app'; and also import 'firebase/compat/firestore';. And works!
Im trying to upload an image to Firebase storage. When i try to upload the image, i get the error as 404, but i have created the storage in firebase.
Firebase npm version : firebase": "^7.24.0
Error:
code: 404
message: "Not Found. Could not access bucket \"<project>.appspot.com\""
status: "ACCESS_BUCKET"
Storage Rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
Firebase Initialization:
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
});
export const analytics = app.analytics();
export const storage = firebase.storage();
export default app;
Service JS :
export async function uploadImageCloud(image){
const storageRef = storage.ref("image/" + image.name);
return storageRef.put(image);
}
Upload function:
function uploadImage(){
setDataImageUploading(true);
uploadImageCloud(getDataImage).then((data)=>{
console.log(data);
setDataImageUploading(false);
}).catch((e)=>{
console.log(e);
setDataImageUploading(false);
});
}
Any idea where did i messed up?
I had the same issue and finally I found out that the value of the storageBucket passed to initializeApp is very sensitive data. It should be exactly the bucket name on the top files(without gs://):
in this project for example it is steem-engine-dex.appspot.com.
const app = firebase.initializeApp({
//...
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
//...
});
Important:
storageBucket is case sensitive. e.g. steem-engine-dex.appSpot.com is invalid
storageBucket shouldn't include any extra space in beginning or end. e.g. steem-engine-dex.appspot.com and steem-engine-dex.appspot.com are invalid
I am doing a small project with Google authentication. Now, this is my first time doing this, so I might be doing something wrong which I am not seeing. I did the following steps:
-I went on firebase and linked my account
-I enabled google to be able to use it for authentication
-I pasted the project data in my file, as I will show in a bit
-and I put the code for the autentication
<script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyArVSWB1OYZYQJEkmc6uIi9jyfmRIW1oSk",
authDomain: "assignment-da42d.firebaseapp.com",
databaseURL: "https://assignment-da42d.firebaseio.com",
projectId: "assignment-da42d",
storageBucket: "assignment-da42d.appspot.com",
messagingSenderId: "569189156463",
appId: "",
measurementId: "G-N6D1788RXF"
};
firebase.initializeApp(firebaseConfig);
function googleSignIn(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider)
}
</script>
<button onclick="googleSignIn()">Google Sign in</button>
However, even after following multiple tutorials, using the same methods, I kept getting the error:
Uncaught TypeError: Cannot read property 'GoogleAuthProvider' of undefined
What am I doing wrong please?
I had the same issues late week and I've since solved it.
Can you point out where you include the following or some other version of the auth library?
<script src="/__/firebase/[version number]/firebase-auth.js"></script>
If that's missing you can paste it in before your code.
I installed the whole package - $ npm install --save firebase
and my config file looks like
import firebase from "firebase/app";
import "firebase/storage";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "......",
authDomain: ".....",
databaseURL: ".....",
projectId: ".....",
storageBucket: ".....",
messagingSenderId: "......",
appId: "......",
measurementId: "...."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const projectStorage = firebase.storage();
export const projectFirestore = firebase.firestore();
export const timestamp = firebase.firestore.FieldValue.serverTimestamp;
export const auth = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () =>{
auth.signInWithRedirect(provider).then(function(){
});
};
and I can call
const logIn = () => {
let ret = signInWithGoogle();
console.log(ret);
getCredentials();
}
in the navbar.
Here is my code:
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<from firebase>",
authDomain: "<from firebase>",
databaseURL: "<from firebase>",
projectId: "<from firebase>",
storageBucket: "",
messagingSenderId: "<from firebase>",
appId: "<from firebase>"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// [START get_messaging_object]
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
</script>
This line firebase.messaging(); throws:
Uncaught TypeError: firebase.messaging is not a function at
Noted that the result of console.log(firebase) is:
Any idea what's the problem?
It looks like you didn't follow the basic integration steps from the documentation. There is an include for messaging:
<script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-messaging.js"></script>
You must included import '#firebase/messaging' for it to work. So it's supposed to look like this:
import * as firebase from 'firebase/app';
import '#firebase/messaging';
Original answerd:
TypeError: firebase.messaging is not a function in node.js
I tried to upload a file(image) on firebase storage. but it consoles an error saying "Uncaught Error: No Storage Bucket defined in Firebase Options." . This is my code
const fileUpBtn = document.getElementById('photoUpload');
const selectFile = document.getElementById('selectedFile');
const postIt = document.getElementById('postIt');
fileUpBtn.addEventListener('click',function(){
selectFile.click();
}
);
selectFile.addEventListener('change',function(e){
var file=e.target.files[0];
var filename = file.name;
console.log('/postPic/'+filename);
var storeLocation = storage.ref('/postPic/'+filename);
var uploadTask=storeLocation.put(file);
});
I tried by allowing storage for any users but that situation also consoles this error.
It's likely the "storageBucket" option in the Firebase config is an empty string. It seems to default to an empty string unless "Storage" has been initialized on the console interface.
Go to your firebase console, initialize "Storage" by accessing it on the Firebase console interface, and then copy the new value for "storageBucket" from the firebase config into your app.
Your firebase config should look something like this.
{
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "my-app-a123z.firebaseapp.com",
databaseURL: "https://my-app-a123z.firebaseio.com",
projectId: "my-app-a123z",
storageBucket: "my-app-a123z.appspot.com",
messagingSenderId: "123456789012"
};
If you got this issue working on angular. You must specify the storageBucket link on your enviroment.prod.ts Since when you deploy your project, it will use the production variables and files.
export const environment = {
production: true,
firebaseConfig : {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "your-app_name.firebaseapp.com",
databaseURL: "https://your-app_name.firebaseio.com",
projectId: "your-app_name",
storageBucket: "gs://your-app_name.appspot.com/", //REMEMBER TO ADD IT HERE
messagingSenderId: "604005378047",
appId: "1:604005378047:web:ab0cdef3gh123456"
}};