Firebase Databases and Vue
One of the key principles of software engineering is DRY, or in long form: Do Not Repeat Yourself. It’s a principle that prevents errors, reduces the size of your code, and makes refactoring easier. In near direct opposition to this is the poor standard of coding on the web. Tutorials are full of examples that encourage you to do exactly the opposite, to repeat yourself, and given the scarcity of good example architectures it’s easy to fall into bad habits.
I’ve currently got a small Vue.JS side project I’m using to test out various technologies, a small notes web app. I originally wrote it to test out VueX, a state library for Vue, but I’m in the process of refactoring it to use Firebase to persistently store notes and to authenticate users.
A number of tutorials have had trouble with the concept of a global instance of the firebase database object. I’ve seen it stored within the VueX store (which causes mutations not caused by actions, clutters your store, and makes it unnecessarily hard to access it) and I’ve also seen it created once (or more!) per route. Both of these patterns are abusing the intent of the object.
Here’s a much simpler pattern:
firebase.config.js
import Firebase from 'firebase'
const config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
}
export const firebaseApp = Firebase.initializeApp(config)
export const database = firebaseApp.database()
MyComponent.vue
<script>
import { database } from './firebase.config'
export default {
firebase {
example: database.ref('items')
}
}
</script>
This takes advantage of ES6 classes. The creation of database occurs exactly once when the module is first loaded and then the same object is made available to all other imports of database. This prevents you unnecessarily committing your database to VueX and the bad code smell of repeated instantiation.