'Firebase SDK V9 auto-configuration with /__/firebase/init.js
After moving to the modular SDK V9 auto-configuration does not work any more using /__/firebase/init.js
. It's expected as init.js
contains the old initialization schema.
Unfortunately it is not mentioned neither in the documentation nor in the migration guide how to make auto-configuration work in the V9.
Solution 1:[1]
For now, the V9 SDKs only work with the explicit configuration snippet (which you can get from the Firebase console and from your site's __/firebase/init.json
).
Unfortunately, since the __/firebase/init.js
and __/firebase/init.json
is provided by Firebase Hosting at run-time, it's not really compatible with tree-shaking (which is the primary reason for the modular SDKs).
Solution 2:[2]
You can fetch /__/firebase/init.json
at runtime but then you have to deal with initializeApp(firebaseConfig)
being a promise or top-level await which isn't well supported in tooling yet.
import { initializeApp } from 'firebase/app';
const response = await fetch('/__/firebase/init.json');
const firebaseApp = initializeApp(await response.json());
It's a hack but you could also work around this with /__/firebase/init.js
.
<script>
// Capture the config object from /__/firebase/init.js
window.firebase = {
initializeApp: (config) => {
window.firebaseConfig = config;
// Delete fake Firebase global
delete window.firebase;
},
};
</script>
<script src="/__/firebase/init.js"></script>
<script type="module">
import { initializeApp } from 'firebase/app';
const firebaseConfig = window.firebaseConfig;
if (!firebaseConfig) {
throw new Error('window.firebaseConfig is not defined');
}
const firebaseApp = initializeApp(firebaseConfig);
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kiana |
Solution 2 | abraham |