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);
});
});
Related
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.
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 have a react-create-app application, in which I used firebase for pushnotification. Recently I upgraded firebase from 8.* to 9.*. While getting push token, it throws the following error:
FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://9fd5-49-204-137-92.ngrok.io/firebase-cloud-messaging-push-scope') with script ('https://9fd5-49-204-137-92.ngrok.io/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html'). (messaging/failed-service-worker-registration).
In firebase.js, I have the following code set, which throws the above mentioned error
import { initializeApp } from "firebase/app"
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const message_key = "key"
var firebaseConfig = {
apiKey: "apikey",
authDomain: "authdomain",
projectId: "project-app",
storageBucket: "******.com",
messagingSenderId: "id",
appId: "appid",
measurementId: "mid"
};
const firebaseApp = initializeApp(firebaseConfig);
let messaging = getMessaging(firebaseApp);
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register(process.env.PUBLIC_URL + "/firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration);
getToken({messaging, vapidKey: message_key})
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
})
.catch(function(err) {
console.log("Service worker registration failed, error:", err);
});
}}
How can I solve this issue?
Moving firebase-messaging-sw.js file to public directory solved the above issue.
the data loading good, but when I keep the page for half hour without any actions and then trying to load data without refreshing page - I'm getting this error. I've found similar issue here and added firebase.firestore().enablePersistence(). It didn't help. The other weird observation, even when the data loading successfully I'm often observe in network this error
My firebase config:
import firebase from "firebase";
const config = {
apiKey: "AIzaSyC**********1vY38Q",
authDomain: "****.firebaseapp.com",
databaseURL: "https://********",
projectId: "myproject",
storageBucket: "****.appspot.com",
messagingSenderId: "209382989",
appId: "1:1**********ceda27",
measurementId: "G*****B96",
};
firebase.initializeApp(config);
firebase.firestore().enablePersistence();
export const db = firebase.firestore();
export default firebase;
My request:
import firebase, { db } from "./firebase.config";
const getData = async (db, collection, docId) => {
const data = await db.collection(collection).doc(docId.toString()).get();
return { data: data.data()?.history.map((con) => ({ ...con, profileId: docId, names: {} })) || [], docId };
};
export const getCollectionData = async (collection, docIdArray) => {
try {
await firebase.auth().signInAnonymously();
return new Promise((resolve, reject) => {
console.log("in promise");
firebase.auth().onAuthStateChanged(async (user) => {
if (user) {
try {
const data = await Promise.all((docIdArray.map((docId) => getData(db, collection, docId))));
resolve(data);
} catch (error) {
reject(error);
}
} else {
console.log("user is signed out");
// User is signed out
// ...
}
});
});
} catch (error) {
console.log.apply(error);
}
};
after page reloading it works fine. 403 error sometimes dissappeared sometimes not. Does anybody faced something similar?
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.