When adding Firebase to a Flutter app, we need to add google-services.json
on Android and GoogleService.plist
on iOS.
A similar setup is required on web. We can copy this script from the Firebase project settings, and add it to the body
tag of the generated index.html
file:
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<your-api-key>",
authDomain: "<your-auth-domain>",
databaseURL: "<your-database-url>",
projectId: "<your-project-id>",
storageBucket: "<your-storage-bucket>",
messagingSenderId: "<your-messaging-sender-id>",
appId: "<your-app-id>",
measurementId: "<your-measurement-id>"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
However, all the values inside firebaseConfig
are better stored inside a separate file. This can be very useful for public open source projects, so that we don't share our Firebase config details with the whole world. 😉
To solve this, we can move the generated firebaseConfig
variable into a ./firebase-config.js
file in our project (make sure to use export
):
export var firebaseConfig = {
apiKey: "<your-api-key>",
authDomain: "<your-auth-domain>",
databaseURL: "<your-database-url>",
projectId: "<your-project-id>",
storageBucket: "<your-storage-bucket>",
messagingSenderId: "<your-messaging-sender-id>",
appId: "<your-app-id>",
measurementId: "<your-measurement-id>"
};
We can then import this in the index.html
file:
<script src="./firebase-config.js"></script>
<!-- https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file -->
<script type="module">
// Your web app's Firebase configuration
import { firebaseConfig } from './firebase-config.js';
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
Finally, we can hide the config file from git, by adding it to .gitignore
:
# web
web/firebase-config.js
Voilà ! We can now commit and push, safe in the knowledge that firebase-config.js
will remain private to us.
NOTE: This does not prevent end-users from seeing the configuration variables, because once the web app is loaded, it's easy to inspect all the loaded Javascript code. Still, it's useful to not commit this code when sharing open source projects, as I have done here.
Happy coding!