service firestore is not available - javascript

I'm trying to connect to my firestore using plain javascript. (I wanna get up to speed and running for now)
index.js:
import app from './firebase.js'
import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-firestore.js'
const db = getFirestore(app)
However, this throws an error: Uncaught Error: Service firestore is not available
firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = {
// configs
};
// Initialize Firebase
let app
export default app = initializeApp(firebaseConfig);
Then I import the script in my index.html:
<!DOCTYPE html>
....
<script type="module" src="index.html"></script>
Note: I can read and write to the firestore using firebase web interface.

So if you want to use plain js (without bundlers like webpack), you would need to put your JS code into script tag like so:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = { ... };
const app = initializeApp(firebaseConfig);
</script>
Otherwise, if you want to use it like you intended to do so, you would need to:
install a firebase package
a module bundler (e.g. webpack) to bundle the files for you

Using npm, but got the same error message.
Restarted terminal & uninstalled and reinstall firebase, then worked...not sure which one that did it though.

You need to upgrade your firestore version 9.0.0 to 9.4.0 and it work fine
import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-firestore.js";

Change your import link import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
to import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
just update the firebase version from 9.0.0 to 9.0.1

Related

Uncaught SyntaxError: Cannot use import statement outside a module (Using Firebase)

I'm having a problem storing data to my database through my html form, The error I get comes from my import statement which is: Uncaught SyntaxError: Cannot use import statement outside a module!
Code below:
import {
initializeApp
} from "firebase/app";
const firebaseConfig = {
apiKey: "MY_API_KEY", //actual values are in my code, changed here for security purposes.
authDomain: "My_auth_Domain",
databaseURL: "FirebaseDb_URL",
projectId: "Project_id",
storageBucket: "storageBucket",
messagingSenderId: "SenderId",
appId: "appId"
};
const app = initializeApp(firebaseConfig);
let inviteInfo = firebase.database().ref("inviteinfos");
document.getElementById("#regform", submitForm);
function submitForm(e) {
let name = document.getElementsByName("fullname").value;
let compName = document.getElementsByName("compName").value;
let email = document.getElementsByName("email").value;
let address = document.getElementsByName("address").value;
let contact = document.getElementsByName("contact").value;
console.log(name, compName, email, address, contact);
saveContactInfo(name, compName, email, address, contact);
document.getElementById("#regform").reset();
}
What I have tried so far:
changed import statement to the following
const {initializeApp} = require("firebase/app");
used import with firebase provided link
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
used const with the firebase provided link:
const {initializeApp} = require("https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js");
Moved js from app.js into the main html page with a script tag of type module.
used npm to install firebase to retrieve the modules.
in regards to the link based solution I tried to remove the -app to see if it made a difference but it did not.
So far none of these have worked for me, the table I am trying to store information to currently does not exist but research has shown that running even without the table existing will create the table automatically for me.
Load app.js like this:
<script type="module" src="./app.js"></script>
Inside app.js, you import firebase-app like this:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
// ...
Here's an example (I can't use a separate file for app.js, but this demonstrates that it does work):
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
// Check that it worked and returned a function:
console.log(typeof initializeApp); // "function"
</script>
You don't need a script tag for firebase-app.js at all, it'll get loaded by the browser because of your import.
Note that this will be using modules natively in the browser. All modern browsers directly support doing that, but obsolete ones like Internet Explorer don't, and separately loading modules like this can involve lots of small HTTP calls rather than a few larger ones, which can cause page load delays even with modern net protocols like SPDY. For that reason, people often use bundlers like Vite, Rollup, Webpack, etc. that combine modules into a small number of bundle files. If you like, you could look at doing that. But again, modern browsers natively support modules, so you don't have to.
Using "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js" in every place you want to import from firebase-app may be a bit of a pain. You have two options to make it easier:
1. In Chromium-based browsers (only, sadly, for now), you can use an import map:
<script type="importmap">
{
"imports": {
"firebase-app": "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js"
}
}
</script>
That tells your browser that when you import from "firebase/app", it should use "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js".
Live Example:
<script type="importmap">
{
"imports": {
"firebase/app": "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js"
}
}
</script>
<script type="module">
import { initializeApp } from "firebase/app";
// Check that it worked and returned a function:
console.log(typeof initializeApp); // "function"
</script>
2. If you can't use import maps, you can write a module that re-exports everything from firebase-app, and then import from that module in your code rather than directly from firebase-app:
Your own local firebase-app.js file:
// This re-exports all of its named exports (but not its default, if any)
export * from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
/* firebase-app.js doesn't provide a default export. If it did, this is
how you'd re-export it:
export { default } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
*/
Then app.js would use firebase-app.js:
import { initializeApp } from "./firebase-app.js";
(I can't do a live example of that with Stack Snippets, but here's that on CodeSandbox.)

Firebase currentUser and onAuthStateChanged

I am developing an app using react native, every time I refresh the app on the emulator in onAuthStateChanged and currentUser from firebase I get null.
I have read about waiting onAuthStateChanged to get a status update but I never do, so I guess I misconfigured something.
I am using expo 44, react 17, firebase 9.6.5 but in compat mode (planning in fully migrate later)
My first attempt of solution was trying to add persistence: firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";
import AsyncStorage from "#react-native-async-storage/async-storage";
import { firebaseConfig } from "./firebase/firebaseConfig";
firebase.initializeApp(firebaseConfig);
firebase.firestore();
firebase.functions();
firebase.storage();
firebase.auth();
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
firebase.auth().onAuthStateChanged(async (user) => {
console.log("onAuthStateChanged called: ", user);
if (user) {
await AsyncStorage.setItem('#isLoggedIn', '1');
} else {
await AsyncStorage.setItem('#isLoggedIn', '0');
}
});
export default firebase;
But I get an error:
undefined is not an object (evaluating 'this.storage.setItem')
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:5248:0 in verifyBeforeUpdateEmail
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:5420:12 in _fromIdTokenResponse
at http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:183132:41 in _set
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1414:55 in newData.some$argument_0
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:2060:1 in <global>
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:2047:30 in _isIOS
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
to Login I use:
userCredential = firebase
.auth()
.signInWithEmailAndPassword(data.email, this.state.password);
I had this exact same issue. I solved it by adding "firebase": "^8.9.1" to package.json, running yarn install and changing the import import firebase from "firebase" (remove all the other imports you have). Apparently selective imports have a bug in v8, but at least it works well :)

Import firebase firestore from CDN JS not working

I am importing Firebase Firestore from CDN to run on a local server. I imported it as the documentation says, right here: https://firebase.google.com/docs/web/alt-setup
My code :
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
import { firestore } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-firestore.js'
The problem:
Firebase app and firebase auth are imported and work perfectly however, Firestore is not being imported. I get this error:
Uncaught SyntaxError: The requested module 'https://www.gstatic.com/firebasejs/9.6.3/firebase-firestore.js' does not provide an export named 'firestore'
This is my first web project using firebase and I dont know how to move forward. Any help or suggestion will be appreciated by this newbie. If you need anymore information let me know, Thanks.
One way to import is, first create a file called firebase.js and paste this code :
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getFirestore, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js";
//add your credentials from firebase project
const firebaseConfig = {
apiKey: "YOUR-apiKey-nCVgNHJXTs",
authDomain: "YOUR-authDomain.firebaseapp.com",
projectId: "YOUR-projectId-fb",
storageBucket: "YOUR-storageBucket-fb.appspot.com",
messagingSenderId: "YOUR-messagingSenderId",
appId: "YOUR-appId-web:11c8d54e0"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
//create your custom method
export const getWolfs = () => {
return getDocs(collection(db, "yourNameCollection"));
};
Now, you can create a new file called main.js and paste this code:
import { getWolfs } from './firebase.js';
//suppose you want to display the list of wolves in the browser console
window.addEventListener("DOMContentLoaded", async (e) => {
const querySnapshot = await getWolfs();
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
});
Finally create the html file index.html and paste this code:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>firebase</title>
</head>
<body>
<h2>wolves</h2>
<!--main app-->
<script type="module" src="./main.js"></script>
</body>
</html>
Sample project:
That is all, i hope it works for you 😉
I think the source has been deprecated. Cause the explanation written like this, from this source https://firebase.google.com/docs/web/alt-setup#from-the-cdn
For most Firebase Web apps we strongly recommend using SDK version 9 via npm.
I found two ways, in version 8 you can still use that way.
<body>
<!-- Insert this script at the bottom of the HTML, but before you use any Firebase services -->
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
</body>
But if you want use in version 9, you have to use npm.
npm install firebase#9.4.1 --save
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
You can visit: https://firebase.google.com/docs/firestore/quickstart#web-version-9
Hopefully this can help you.
Have you type this in script tag
<body>
<script type="module">
// ...
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
</script>
</body>
type=module ?
Try this, this issue similar with you
import { function } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-SERVICE.js'
//Example
import { function } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-firestore.js'
Yes, it does not provide an export named 'firestore' but
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.n.n/firebase-firestore.js";
const firestore = getFirestore();
console.log(firestore);
does.
See: getFirestore()

firebase.apps.length of undefined

Environment
Operating System version: Windows 11
Browser version: Chrome
Firebase SDK version: 9.0.2
Firebase Product: database
firebase.apps.length of undefined
Issue:
I dont know what happened today morning it opened my code and it shows something like
app.firestore() is not a function and shows firebase.apps.length of undefined
Code:
import * as firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app()
const db = app.firestore()
The syntax for Firebase has changed in v9, as everything is now modular/functional. You can now safely get an app with:
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
I highly recommend keeping Firebase's own documentation and this upgrade guide handy.
Alternatively, you can keep using the older syntax by using the compatibility mode of the newer SDKs, by importing from the compat path.
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
In that case the rest of your code stays unchanged.

How to enable `ignoreUndefinedProperties` in node js

I am developing a REST api for my application in Nodejs and Express. But each time i try to send a request I get an undefined error. Please how can i enable 'ignoreundefinedproperties'
once you import the firebase-admin sdk (in Typescript) like this
import * as firestore from "firebase-admin";
then you just need to set the setting like this :
const db = firestore.firestore();
db.settings({ ignoreUndefinedProperties: true })
If you are getting errors for calling this more than once, I recommend putting admin.firestore().settings({ignoreUndefinedProperties:true}); in the same place you have admin.initializeApp();
Here's how I did it in my Typescript project
initialize.ts:
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
admin.firestore().settings({ignoreUndefinedProperties:true});
Top of index.ts:
import './initialize.ts'
For anyone using the v9 API:
import { getFirestore, connectFirestoreEmulator, initializeFirestore } from 'firebase/firestore'; // Firebase v9+
// Must be called before getFirestore()
initializeFirestore(app, {
ignoreUndefinedProperties: true
});
const firestore = getFirestore(app);
If you're facing error (Firestore has already been initialized. You can only call settings() once) even after trying other answers, restart your IDE/VSCode and terminal. This is what worked for me.

Categories