Firebase
Often referred to as Backend as a Service (BaaS), Firebase minimizes the work involved in managing user accounts and databases, allowing developers to focus on building the frontend(web and mobile) without the burden to set up and maintain a backend infrastructure.
It started as a real-time database service, then was bought by Google in 2014. Over time, Firebase expanded its offerings to include authentication, cloud storage, cloud functions, and more, becoming a comprehensive mobile/web app development platform.
Get Started
Go to firebase console and create a project.
It will generate the setup code for you, depend on your platform, like following for web:
<script type="module">
import { initializeApp }
from "https://www.gstatic.com/firebasejs/10.13.2/firebase-app.js";
const firebaseConfig = {
apiKey: "VJ4zTzfNe1v1kz9xeg_WjCI6yWSu8-uudLPwKD1",
authDomain: "project-id.firebaseapp.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "12345678901",
appId: "1:12345678901:web:3pvzJkqknm8x3cubfxcrrb"
};
const app = initializeApp(firebaseConfig);
</script>
Authentication
Firebase supports multiple sign-in methods, including email/password and various OAuth providers like Google, Facebook, and Twitter. To use a particular method, you need to enable it in the Firebase console first.
I prefer OAuth over email/password sign-in. You don't have to manage user accounts, it's also more secure, and it offers better user experience. Let's take Google as example:
import { getAuth, GoogleAuthProvider, signInWithPopup }
from 'https://www.gstatic.com/firebasejs/10.13.2/firebase-auth.js'
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
signInWithPopup(auth, provider)
.then(result => {
const user = result.user;
}).catch(err => {
alert("Sign-in not successful.")
});
Database
At it's core is the Cloud Firestore, it's a document database, like MongoDB, it's schemaless, very flexible and easy to get started with.
import { getFirestore, collection, getDocs }
from 'https://www.gstatic.com/firebasejs/10.13.2/firebase-firestore.js'
const db = getFirestore(app);
async function getItems(db) {
const snapshot = await getDocs(collection(db, 'items'));
return snapshot.docs.map(doc => doc.data());
}
Security Considerations
Have you noticed that Firebase's apiKey is in your code? Normally,
we don't put keys in our code, especially in client-side code. But for
Firebase, it's inevitable.
This looks dangerous, but that doesn’t mean all your data is visible to an attacker. They still need to log in to access the data.
Firebase has built-in security rules that help protect your data. You should always define those rules to ensure that only authenticated users can access or modify your data as needed.
Supabase
Supabase is a alternative to Firebase built on PostgreSQL, and it's opensource.