# Firebase
Because I used it free, so it deserved free PR here
Firebase helps mobile and web app teams succeed
All of things, I'm concerned about Firebase, are relevant to web.
# Install
Full doc here (opens new window)
# 1. SDK JS
npm install --save firebase
# 2. Choose Products
To include only specific Firebase products (like Authentication and Database Realtime),
// Firebase App (the core Firebase SDK)
// is always required and must be listed first
import * as firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/database";
# 3. Initilize App
Assume we need to set up Database Realtime
See here (opens new window) for more detail
// Set the configuration for your app
// TODO: Replace with your project's config object
var config = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com",
storageBucket: "bucket.appspot.com",
appId: "app-id",
};
firebase.initializeApp(config);
# authentication
Let's choose Google for example
# 1. Create Provider
var authProvider = new firebase.auth.GoogleAuthProvider();
# 2. Request Sign In
var result = await firebase.auth().signInWithPopup(authProvider);
// after user authenicated, you will have some info below
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
Or you can receive the result through the hook
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
} else {
// User is signed out.
}
});
# Database Realtime
# 1. Add Config
The same with Step 3 in Install . Then,
// Get a reference to the database service
var database = firebase.database();
# 2. Read
Assume we have data structure like this:
{
"categories": {
"cat_id1": {
// cat data
},
"cat_id2": {
// cat data
},
},
"users": {
"user_id1": {
// data
}
}
}
Then our code looks like this:
# 3. Write
# 4. Sercurity Rule
categories
: can be only read from the outside and manage in Firebase Consoleusers
: user can only read & write on his own data
{
"rules": {
"categories": {
".read": true,
},
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}