I want to post an image to Firebase Storage. My React app is on Netlify.
Firebase Config file.
The environment variables are set on Netlify.
import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage"
const firebaseConfig = {
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 app = initializeApp(firebaseConfig);
export const storage = getStorage(app)
This is where I am uploading the image
import { storage } from '../../firebase';
import { ref, uploadBytes, getDownloadURL } from "firebase/storage"
const uploadToFirebase = async (newPost) => {
if (postImage == null) return;
const imageRef = ref(storage, `images/${postImage.name + v4()}`)
await uploadBytes(imageRef, postImage)
const url = await getDownloadURL(imageRef)
newPost.post.image = url
}
when i click on the upload button on the site, i get these errors
POST https://firebasestorage.googleapis.com/v0/b/***/o?name=images%2FScreenshot%20(5).pngfc61b7f6-da0d-40f3-a3e5-864e27810503 404
Uncaught (in promise) FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
The error payload says 404 not found
Firebase Storage Rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
PS: This code works locally
I thought there might be a problem with the environment variables so tried hardcoding them the problem persisted.
Related
My main problem currently in my react native app is that every-time i do a npx expo start and start the app it gives me the error:
ERROR FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been
created - call Firebase App.initializeApp() (app/no-app).
This error is weird because ive already tried calling firebase at the very end of my firebase.js file and at the top..and it still says there is no default app created..How would i fix this?(error suddenly happened a couple days ago for some reason). another error im getting is also this:
ERROR Invariant Violation: "main" has not been registered. This can
happen if:
Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
current code:
import { initializeApp } from "firebase/app";
import { getAuth, createUserWithEmailAndPassword,signOut} from "firebase/auth";
const firebaseConfig = {
apiKey: "already filled out ",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
}; // filled this out not putting the actual variables for security reasons
export const auth = getAuth();
let myApp = initializeApp(firebaseConfig);
export function createUser (auth, email, password) {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
}
export default function signOutUser () {
signOut(auth).then(() => {
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
}
I am currently setting up push notifications on my react/firebase project.
I have followed all the steps and added the firebase-messaging-sw.js, getToken etc..
I used to be able to get a FCM token back from getToken but I am no longer able to do so due to this error message:
An error occurred while retrieving token. FirebaseError: Messaging:
A problem occurred while subscribing the user to FCM: Request contains an invalid argument.
(messaging/token-subscribe-failed).
at requestGetToken (requests.ts:67:1)
at async getNewToken (token-manager.ts:139:1)
This error occurs when I call the getTokenFound() method
Before when this was working, I would also have problems with the service worker if I was running the same project on a different system. Only my main development system was able to not hit the service worker error:
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope
('http://localhost:3000/firebase-cloud-messaging-push-scope%27) with script
('http://localhost:3000/firebase-messaging-sw.js%27): ServiceWorker script evaluation failed
(messaging/failed-service-worker-registration).
Two two issues seem to be persistent, often it seems like an error loop happens if I deny the notification permissions and then try to allow them again, I would get the invalid argument error.
Here are my relevant code blocks below, I'm really not sure what else to change here. The react setup for push notifications seems very inconsistent depending on what machine Im on. Many thanks for any insight!
firebase-messaging-sw.js (in public dir with index.html)
importScripts('https://www.gstatic.com/firebasejs/8.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.1/firebase-messaging.js');
const firebaseConfig = {
apiKey: DATA,
authDomain: DATA,
databaseURL: DATA,
projectId: DATA,
storageBucket: DATA,
messagingSenderId: DATA,
appId: DATA,
measurementId: DATA
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log("Received background message ", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "../src/assets/image/default.svg",
tag: "notification-1"
};
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
firebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getFunctions } from "firebase/functions";
import { getStorage } from "firebase/storage";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import 'firebase/storage';
export const app = initializeApp({
apiKey: data,
authDomain: data,
databaseURL: data,
projectId: data,
storageBucket: data,
messagingSenderId: data,
appId: data,
measurementId: data
});
export const messaging = getMessaging(app);
export const firestore = getFirestore(app);
export const functions = getFunctions(app);
export const storage = getStorage(app);
export const getTokenFound = async () => {
let currentToken = "";
try {
currentToken = await getToken(messaging, { vapidKey: myVapidKey});
if (currentToken) {
console.log("CURRENT TOKEN", currentToken)
} else {
}
} catch (error) {
console.log("An error occurred while retrieving token. ", error);
}
return currentToken;
};
export const onMessageListener = () =>
new Promise((resolve) => {
onMessage(messaging, (payload) => {
console.log("payload", payload)
resolve(payload);
});
});
I am trying to make a social media app. I wanted to add a feature of uploading pictures but I don't know how to fetch those pictures in my firebase storage and display all of them as a post on my app.
This is my firebase.js file
import firebase from "firebase/app";
import "firebase/storage";
const firebaseConfig = {
apiKey: "AIzaSyCbiHH-zpob5AytooHMxrB_oncIz5wAcgg",
authDomain: "expresate-react.firebaseapp.com",
databaseURL: "https://expresate-react-default-rtdb.firebaseio.com",
projectId: "expresate-react",
storageBucket: "expresate-react.appspot.com",
messagingSenderId: "400618187775",
appId: "1:400618187775:web:d78270044e4b1d464215ca"
};
firebase.initializeApp(firebaseConfig);
const storage = firebase.storage();
export { storage, firebase as default };
This is the function which uploads the image on the firebase storage.
const image = this.state.selectedFile;
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
"state_changed",
snapshot => {},
error => {
console.log(error);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
this.setState({url: url, selectedFile: null});
});
}
);
The upload feature is working perfectly I can see the files in firebase storage. Now, how do I fetch them and display them on my app?
Thank you
You already get the url with getDownloadURL.
It is an url like this one.
You can use that to display your image. Just put that url into a img like here:
<img src={url} />
I am trying to connect my ReactJs app to firebase to implement push notifications. Every time I try to console log the token that I get from firebase, this error always shows up and I don't know how I can solve it. Here is a screenshot of the error :
I added the following lines in my firebase-messaging-sw.js which is located inside my public file and here it is :
importScripts('https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js');
importScripts('https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js');
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function (registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function (err) {
console.log('Service worker registration failed, error:', err);
});
}
firebase.initializeApp({
messagingSenderId: "msg_id",
})
const initMessaging = firebase.messaging()
There is also the file firebase.js and its content which I get the data inside the config object from my firebase project which is already registered :
import firebase from "firebase";
const config = {
apiKey: "my_api_key",
authDomain: "my_domain",
databaseURL: "my_database_url",
projectId: "project_id",
storageBucket: "storage-bucket",
messagingSenderId: "msg_id",
appId: "app_id",
measurementId: "measure_id"
}
firebase.initializeApp(config);
firebase.analytics();
export default firebase;
And here is my useEffect where I am trying to print the token :
useEffect(() => {
const messaging = firebase.messaging();
messaging.requestPermission().then(() => {
return messaging.getToken()
}).then(token => {
console.log("TOKEN :", token)
})
}, [])
I tried many fixes and nothing worked and I still get the same error. I hope that anyone can help me with this. Thanks in advance.
I am following the react native firebase docs (https://rnfirebase.io/docs/v5.x.x/auth/phone-auth) on Phone Authorization and am confused about the need (or no need) for reCAPTCHA.
The docs do not pass a second parameter to the signInWithPhoneNumber() method but when calling the method I receive an error asking for the recaptchaVerifier as the second parameter. Because I am writing the app for both iOs and Android I utilized the Web connection to Firebase and am not using the generated JSON file. I believe this is my issue as it thinks I am calling the API from a non-mobile device.
Is Firebase Web the best way to connect a React Native cross platform application? If it is, is there a way to generate the reCAPTCHA code?
The firebase docs talk about an invisible reCAPTCHA but they only provide code for HTML with a button ID and whatnot. (I did try to give and an ID as a prop but found no success) https://firebase.google.com/docs/auth/web/phone-auth
My config file:
import firebase from 'firebase';
class Config {
constructor() {
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "AIaskdjf93rlaksdjf99999",
authDomain: "myDomain.firebaseapp.com",
databaseURL: "https://myDomain.firebaseio.com",
projectId: "myDomain",
storageBucket: "",
messagingSenderId: "88827277272",
appId: "somenumbersomitted",
measurementId: "akjdsfkljad"
});
}
}
login = async (user, success_callback, failed_callback) => {
await firebase
.auth()
.signInWithEmailAndPassword(user.userName, user.password)
.then(success_callback, failed_callback);
};
//todo:: need to update signInWithPhoneNumber second param to be the recaptcha token
loginWithPhone = async (phoneNumber, success_callback, failed_callback) => {
var applicationVerifier = ?????;
await firebase
.auth()
.signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then(success_callback, failed_callback);
};
//todo: figure out how to get this method to work in RN. Not able to take in button ID...
recaptchaVerifier = async (phoneNumber, success_callback, failed_callback) =>{
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': function(response) {
loginWithPhone(phoneNumber, success_callback, failed_callback);
}
});
};
}
const config = new Config();
export default config;
I managed to get phone number authentication working on React Native by using https://rnfirebase.io/ and the following code:
const sendSmsCode = async (phoneNumber: string) => {
const isUserPhoneNumberLinked = await getIsUserPhoneNumberLinked(
phoneNumber
);
if (!isUserPhoneNumberLinked) {
} else {
try {
let confirmationResult = await firebase
.auth()
.signInWithPhoneNumber(phoneNumber, true);
Promise.resolve();
setIsSmsCodeSent(true);
confirmationRef.current = confirmationResult;
} catch (error) {
throw error;
}
}
};
And then you can use confirmationRef.current.confirm() to confirm the sms code:
const verifySmsCode = async () => {
const result = await confirmationRef.current.confirm(smsCode);
if (result.user) {
dispatch(authenticatedUserAction());
}
};