Firebase Storage Error: 404 - ACCESS_BUCKET - javascript

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

Related

Still get FirebaseError: Request failed with error: Missing or insufficient permissions even all the configs are correct

I'm trying to read from database using below code and Firebase rule;
const firebaseConfig = {
apiKey: "mykey",
authDomain: "mydomain",
projectId: "myprojectid",
storageBucket: "mystoragebucket",
messagingSenderId: "myid",
appId: "myapid",
measurementId: "mymeasurementid",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db: any = getFirestore(app);
// Get a list of cities from your database
async function getCities(db: any) {
const citiesCol = collection(db, "/posts");
const citySnapshot = await getDocs(citiesCol);
const cityList = citySnapshot.docs.map((doc) => doc.data());
return cityList;
}
I get this from Firebase docs, but I still get
FirebaseError: Request failed with error: Missing or insufficient permissions.
I DO NOT want to allow the database for everyone, I want it only myself have permissions. I have this rule on Firebase
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null
}
}
}
What should I do? How can I get rid of this error? There is not even a good answer on the web for "no one can access to the database but myself".

Getting this error Firebase Error (auth/invalid-api-key)

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);

Firebase Cloud Messaging foreground notification not working in Vue

I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
src/App.vue
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
public/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
src/plugins/firebase.js
import firebase from '#firebase/app'
import '#firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
What did I do wrong?
I've found a solution in another QA here in StackOverflow (which I can't find anymore for some reason).
Turns out you have to use Firebase API v7.8.0 instead of 5.5.6 like the docs said at the time. So those first two lines in public/firebase-messaging-sw.js should read like this instead:
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js')
Same issue i was faced. In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different. After set same version in "firebase-messaging-sw.js" importScripts which was in
"package.json", my issue is resolved.
Before change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
After change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
In my case the version on package.json (8.2.1) was different from the actual SDK_VERSION (8.0.1)
After changed service-workers with the same version worked..
I had a bunch of issues setting firebase push notifications for Vue 3 (with Vite), and I had PWA support enabled with vite-plugin-pwa, so it felt like I was flying blind half the time. I was finally able to set up support for PWA, but then I ran into the following issues:
I was getting notifications in the background (when my app was not in focus), but not in the foreground.
When I did get notifications in the background, it appeared twice.
Here's my complete setup. I have the latest firebase as of this post (9.12.1)
// firebase-messaging-sw.js file in the public folder
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-app-compat.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-messaging-compat.js"
);
// Initialize Firebase
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "/icon.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I've seen some posts online provide the onBackgroundMessage here in the service worker, but I experimented with commenting it out and it seemed to fix the issue of notifications appearing twice.
Next, is a firebase.js file with which I retrieve tokens and subsequently listen for foreground notifications.
// firebase.js in same location with main.js
import firebase from "firebase/compat/app";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = firebase.initializeApp(firebaseConfig);
export default getMessaging(app);
And then in main.js
import App from "./App.vue";
import firebaseMessaging from "./firebase";
const app = createApp(App)
app.config.globalProperties.$messaging = firebaseMessaging; //register as a global property
And finally, in App.vue (or wherever you wish to get tokens and send to your serverside)...
import {getToken, onMessage} from "firebase/messaging";
export default {
mounted() {
getToken(this.$messaging, {
vapidKey:
"XXX-XXX",
})
.then((currentToken) => {
if (currentToken) {
console.log("client token", currentToken);
onMessage(this.$messaging, (payload) => {
console.log("Message received. ", payload);
});
//send token to server-side
} else {
console.log(
"No registration token available. Request permission to generate one"
);
}
})
.catch((err) => {
console.log("An error occurred while retrieving token.", err);
});
}
}
Of course don't forget the vapidKey. Took a minute, but it worked perfectly.
For now, I am not offering any opinion as to what the foreground notification should look like, so I am merely logging the payload. But feel free to show it however you deem fit.

Uncaught TypeError: Cannot read property 'GoogleAuthProvider' of undefined cakephp

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.

Uncaught Error: No Storage Bucket defined in Firebase Options. (WEB)

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"
}};

Categories