Operating System version: Mac OS Monterey (but error persists on website hosted on Netlify -- works fine on localhost)
Browser version: Version 1.46.144 Chromium: 108.0.5359.128 (Official Build) (arm64)](https://brave.com/latest/
Firebase SDK version: 9.15.0
When I try and create a doc on the local host, it works fine, but when I try and create one on a hosted site (using netlify), I get this error in the console: #firebase/firestore: Firestore (9.15.0): Connection WebChannel transport errored: nv {type: 'c', target: nm, g: nm, defaultPrevented: false, status: 1}
I've seen that people have used experimentalForceLongPolling to fix the issue with initializeFirebase(), but it gives me an error that a firestore instance already exists.
Firebase.js
// Initialize Firebase
let firebaseApp: FirebaseApp;
try {
firebaseApp = getApp();
} catch (e) {
firebaseApp = initializeApp(firebaseConfig);
}
export const auth = getAuth(firebaseApp);
export const googleProvider = new GoogleAuthProvider();
export const database = getFirestore(firebaseApp);
Here is setting the doc code:
console.log("setting doc");
const dbParams: DBFetchType = {
//#ts-ignore
uid: auth.currentUser.uid,
firstName: signUpDetails.firstName,
lastName: signUpDetails.lastName,
plan: "free-plan",
workspaces: ["Workspace 1"],
charactersUsed: 0,
favorites: [],
};
await setDoc(
doc(
database,
"users",
//#ts-ignore
auth.currentUser.uid
),
dbParams
);
console.log("set doc");
Here is the full console.log:
Related
I just create an example for test Firebase Analytics, I worked before with storage capabilities and every works fine.
This is my code:
<button id="test">Press Me</button>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import {
getAnalytics,
logEvent
} from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-analytics.js';
// Your web app's Firebase configuration
const firebaseConfig = await fetch('../firebaseConfig.json')
.then((response) => response.json());
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Analytics and get a reference to the service
const analytics = getAnalytics(app);
const test = document.getElementById('test');
test.addEventListener('click', () => {
console.log('click', analytics);
logEvent(analytics, 'select_content', {
content_type: 'image',
content_id: 'P12453'
});
});
</script>
My Firebase config includes elements below
{
"apiKey": "xxxx",
"authDomain": "yyyyy.firebaseapp.com",
"projectId": "test-firebase-yyyy",
"storageBucket": "yyyyy.appspot.com",
"messagingSenderId": "123456789",
"appId": "1:123465789:web:qazwsxedc",
"measurementId": "G-qwerty"
}
But it throws next error:
FirebaseError: Installations: Could not process request. Application
offline. (installations/app-offline).
Someone could tell me why ? or where to search? As I mention before storage and cloudstore are working fine.
Thank you.
I'm implementing pusher in a web application using nextjs. It works as expected in my development environment. But it does not work correctly when I deploy it to vercel. I can only see the results when I refresh the page in the browser.
This is the implementation for the client:
useEffect(() => {
const pusher = new Pusher(`${process.env.PUSHER_KEY}`, {
cluster: `${process.env.PUSHER_CLUSTER}`,
useTLS: true
});
const channel = pusher.subscribe('franks-auto-spa');
channel.bind('cancel-wash', data => {
console.log(data.date);
removeWash(data.date);
});
}, []);
And this is the implementation for the API:
export default async (req, res) => {
const connection = await mysql.createConnection(process.env.DATABASE_URL);
console.log(req.body.date);
const result = await connection.query('DELETE FROM ongoing WHERE date = ?', [req.body.date]);
console.log(result);
const pusher = new Pusher({
appId: `${process.env.PUSHER_ID}`,
key: `${process.env.PUSHER_KEY}`,
secret: `${process.env.PUSHER_SECRET}`,
cluster: `${process.env.PUSHER_CLUSTER}`,
useTLS: true
});
pusher.trigger('franks-auto-spa', 'cancel-wash', req.body);
res.json({message: 'Wash deleted deleted...'});
}
Am I missing any configuration in Vercel?
I've had this problem too, once or twice; Vercel times out after a little bit. (10 seconds on Hobby) So using a database with Vercel probably isn't gonna fly. Have you tried switching to the Pro plan? Or you could switch to Heroku, which not only has a longer timeout (30 seconds), but also supports websockets.
I saw many questions on SO regarding this issue and none of them was answered (or the solution doesn't work), I don't know why. People are having this error continuously but no solution is being provided. And from past few days even I'm encountering this error (Note: It seems to be working fine on my physical device (not while debugging, it works on only if I release it), but not on android emulator, so I'm pretty sure my internet is working fine):
Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 3052257ms)
Authorization status: 1
[2022-02-09T07:05:26.500Z] #firebase/firestore: Firestore (9.6.5): Could not reach Cloud Firestore backend. Backend
didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will
operate in offline mode until it is able to successfully connect to the backend.
Authorization status: 1
[2022-02-09T07:08:44.688Z] #firebase/firestore: Firestore (9.6.5): Connection WebChannel transport errored: me {
"defaultPrevented": false,
"g": Y {
"A": true,
"J": null,
"R": [Circular],
"g": $d {
"$": true,
"$a": 2,
"A": 3,
"B": null,
"Ba": 12,
"C": 0,
"D": "gsessionid",
"Da": false,
"Ea": Dd {
"g": Cd {},
},
... & so on...
Package.json:
"#react-native-firebase/app": "^14.3.1",
"#react-native-firebase/messaging": "^14.3.1",
"#react-native-google-signin/google-signin": "^7.0.4",
"expo": "~44.0.0",
"firebase": "^9.6.3",
The authentication & messaging seems to be working fine, but I think the db from firestore is having this issue.
Following is some of the code from my firebase.tsx config file:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, db };
What I tried so far:
Changing the firestore database rules as mentioned in this answer: https://stackoverflow.com/a/70980383/11685381
Using this workaround: https://github.com/firebase/firebase-js-sdk/issues/5667#issuecomment-952079600
I'm not using any .env variables according to this answer: https://stackoverflow.com/a/69095824/11685381
Wiped android emulator data, then Cold Boot. Didn't work.
Upgraded firebase-9.6.3 to firebase-9.6.6. Didn't work.
cleaned the build folder, yarn installed all the packages again. Didn't work.
Can anyone provide any working solution to this problem?
Thank you!
EDIT-1:
The code where I'm calling firestore db especially:
In my HomeScreen.tsx:
import { doc, setDoc, onSnapshot, collection } from "firebase/firestore";
import { db } from "../../../firebase";
// inside functional component
useEffect(() => {
const addUser = () => {
const path = doc(db, "Users", user.uid);
const data = {
_id: user.uid,
name: user.displayName,
email: user.email,
};
setDoc(path, data)
.then(() => {
console.log("User added to db");
})
.catch((err) => {
console.log("Error while adding user to firestore: ", err);
});
};
addUser();
}, []);
useEffect(() => {
const unsub = onSnapshot(collection(db, "Items"), (snapshot) =>
setItems(snapshot.docs.map((doc) => doc.data()))
);
return () => unsub();
}, []);
// so nothing is being displayed here as firestore is not working.
Found out the solution on my own after a lot of search. Although I had to make a new bare react native project from scratch, and even then I was encountering that error, I had literally lost hope with firebase at that point. Then after sometime I changed my firebase config to the below code and it worked:
import {initializeApp} from 'firebase/app';
import {getAuth} from 'firebase/auth';
import {initializeFirestore} from 'firebase/firestore';
const firebaseConfig = {
apiKey: '',
authDomain: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
measurementId: '',
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = initializeFirestore(app, {
experimentalForceLongPolling: true,
});
export {auth, db};
I had to change the initialization of db as mentioned above, hope it works for everyone out there who's stuck on this weird error.
Thank you all for your help!
First config your db, in firestore.js
import firebase, { initializeApp, getApps, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
let app;
if (getApps().length === 0) {
app = initializeApp(firebaseConfig);
} else {
app = getApp();
}
const db = getFirestore(app);
export { db, auth };
Then add collection to the fireStore DB by:
import {db} from "../firebase.js";
import { collection, addDoc } from "firebase/firestore";
const docRef = await addDoc(collection(db, "chats"), {
chatName: input
}).then(() => {
navigation.goBack();
}).catch((error) => alert(error) );
for Reference: https://firebase.google.com/docs/firestore/quickstart
Im trying to get a signedurl from a file in firebase/gc storage. All other solutions that i could find was to create a service account, download the service key, and use it in my app, but ive done that, and im still getting the error. Ive followed this advice also and added relevant roles to my service account SigningError with Firebase getSignedUrl().
The client_email property is in the service key that im using.
Pretty new to service accounts and gc so i may be missing something simple.
I am able to list the buckets, and all other requests to cloud firestore are working. Its just the signedurl for specific files is proving very difficult to retrieve.
Been driving me a bit loopy so any help would be great.
Heres my code.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const { Storage } = require('#google-cloud/storage');
const serviceAccount = require('./emom-84ee4-firebase-adminsdk-2309z-aab93226ec.json');
const keyfileName = require('./emom-84ee4-ac9e94667d5e.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://emom-84ee4.firebaseio.com"
});
const storage = new Storage({
projectId: 'emom-84ee4',
keyFileName: keyfileName,
// TRIED THIS ALSO => keyFileName: serviceAccount
});
const typeDefs = gql`
type DownloadURL {
url: String
}
type Comment {
artist: String,
comment: String,
userId: String,
replies: [Comment]
}
type Track {
album: String,
artist: String,
artistId: String,
description: String,
genre: String,
id: ID,
title: String,
duration: Int,
comments: [Comment]
}
type User {
artist: String,
artistImageUrl: String,
artistName: String,
bio: String,
location: String,
userId: String,
website: String
}
type Query {
tracks: [Track]
users: [User]
downloadUrl: DownloadURL
}
`
const resolvers = {
Query: {
async tracks() {
const tracks = await admin
.firestore()
.collection('tracks')
.get();
return tracks.docs.map(track => track.data());
},
async users() {
const users = await admin
.firestore()
.collection('users')
.get();
return users.docs.map(user => user.data());
},
// ISSUE HAPPENING HERE
async downloadUrl() {
try {
const signedUrl = await storage
.bucket('emom-84ee4.appspot.com')
.file('tracks/ds5MaDn5ewxxvV0CK9GG.mp3')
.getSignedUrl({ action: 'read', expires: '10-25-2022' });
const url = signedUrl;
console.log(url)
return url;
} catch (error) {
console.error(error);
}
}
}
}
const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app, path: '/', cors: true });
exports.graph = functions.https.onRequest(app);
I was getting "Cannot sign data without client_email" error when running firebase emulators:start.
I fixed it by setting up a service account and downloading the service account .json credentials file as service_account.json, then running GOOGLE_APPLICATION_CREDENTIALS="service_account.json" firebase emulators:start
You will need to add your service account key when you initialize your app.
var admin = require("firebase-admin");
var creds = require("[path to your serviceAccountKey.json]");
admin.initializeApp({
credential: admin.credential.cert(creds),
});
If you don't have a service account, you can read how to get it here
or use https://console.firebase.google.com/project/**YOUR_PROJECT**/settings/serviceaccounts/adminsdk
Initializing the Firebase in admin.js:
import * as admin from "firebase-admin";
import serviceAccount from "./serviceAccount";
const options = {
databaseURL: process.env.FIREBASE_DATABASE_URL,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
credential: admin.credential.cert(serviceAccount)
};
admin.initializeApp(options);
export default admin;
Push notification service utilizing the admin.js:
import Firebase from './admin';
const response = await Firebase.messaging().sendToDevice(
notifications.registrationTokens, // tokens for android and iOS devices
notifications.payload // formatted as: notification: { title: '', body: ''}
);
There are two bugs as of now:
1) Push notification not showing up for iOS
2) When the app is running in the background, the push notification gets sent twice to the android device.