- Antoni Górski
- Read in min.
Been wondering how to start with a brand new tool – Google Firebase?
In the following article we’re going to present to you some of Google Firebase functionalities. Once you’re done with the reading, we assure you, that the very basic know-how you’ve possessed is sufficient to integrate it as a backend-as-a-service platform with your front-end application.
Quick look through the content of the article:
- the SDK set up and configuration
- logging in via Google
- some basics you need to know about secure Firestore database
- how to respond to user events
Let’s move on! The whole text is a 2 min read.
Introducing Firebase
Firebase was designed and brought to life by Google. Its ultimate functionality is to either build, release or put through analysis of any kind of web and mobile applications. And what it does, is to accelerate common processes by providing robust solutions available at Firebase Console (an UI tool to manage your app in Firebase) and other related tools. Anything else? Indeed… Its UX, as well as documentation, seems very rich.
SDK Configuration
Firebase SDK is a very powerful tool, which we will use with our application. You can check the official guide here:
Add Firebase to your JavaScript project (google.com)
You may also follow these steps to get started:
- Sign in to the Firebase Console – Firebase console (google.com)
- Click “Add project”
- Enter the project name
- Click “Continue”
- In the center of the Firebase Console project overview page, click the web icon “(</>)”
- Enter the project name once again
- Click “Register app”
… and congratulations! You’ve just created a brand new project!
Now, let’s import the SDK via npm using the following command:
npm install --save firebase@9.0.0-beta.7
Now we should get you a config for your app, shouldn’t we?
- Go to your Project settings in the Firebase Console
- In the “Your apps” tab select the name of the app
- Select “Config” from the Firebase SDK snippet pane
- Copy the config object snippet
And add init (initialize) of Firebase SDK to our app:
import { initializeApp } from "firebase/app" const firebaseConfig = { // paste the config object properties here } const firebaseApp = initializeApp(firebaseConfig);
… you’ve made it to the more pragmatical part of this article. Congrats! From now on we’ll be dealing only with the interesting stuff.
Logging in with Google
Once you make yourself comfortable with the main Firebase Console, you should be able to see the “Build” section, and there is an „Authentication” tab. In this section all essential information about authenticated users are stored, including the „manage” option. For now, let’s just try to add a user to our app.
Go to the “Sign in method” tab and enable the “Google” option. Add the following code to your app:
import { getAuth, GoogleAuthProvider, signInWithPopup} from "firebase/auth"; const provider = new GoogleAuthProvider(); const auth = getAuth(); const result = await signInWithPopup(auth, provider);
And “what does the code do?”, you may ask. It logs you in using an already prepared pop-up. GoogleAuthProvider, getAuth
and signInWithPopup
are the best and easiest options to make it work.
Now, whenever you run your application or log in, you should be able to see the user in the „Authentication” tab.
Firestore is a noSQL database ready for use with the least minimal setup. It offers a collection-document-storing data, where each collection consists of documents, either data or other collections. Simple as that.
The whole database is secured by Rules, which either grant or deny access to particular fragments of the database. They are encrypted with a language similar to JavaScript or JSON.
Now with the help of already logged in user (as we did in previous step), we’re going to prepare the database for storing his data-records. We’re going to start by adding a new collection and then write some Rules.
To add a new collection go to Firebase Console under “Firestore Database” tab and choose “Start collection”. You will be prompted with a pop-up asking for the name of the new collection – just type in “users”. You will also need to provide a sample “user” document. Delete it shortly after it’s been created.
Creating a new collection is successfully completed – now let’s add some Rules.
Go to “Rules” tab and paste the following code:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { function isAuth() { return (request.auth != null) && (request.auth.token.email_verified == true); } function isSelf(id) { return id == request.auth.uid; } match /{collection}/{document=**} { allow read: if false; allow write: if false; } match /users/{userId} { allow get: if isAuth() && isSelf(userId); } } }
Bear in mind that each request sent to the Firestore Database will activate the above-mentioned code and it is up to the Rules whether to allow it, or not. In this case we want to grant access to all of data regarding the user, available only to the user himself. In order to make this work, we just need to implement two functions and two matches.
The “isAuth” function verifies if the user is properly authenticated in our app. The “isSelf” function, however, verifies if requested user data belongs to the user that has actually sent the request.
The request is going to succeed whenever there’s one or more matches allowing it. We disable all the requests in the first match statement and allow getting the user data in the second, providing that certain conditions are met.
Not feeling sure about it? Run a test of the Rules in the simulator – Find more in this related article here: Quickly validate Firebase Security Rules (google.com)
Now let’s take the real users of our app and populate the database with their data. For this purpose we are going to use Firebase Cloud Functions.
Cloud Functions is a NodeJS runtime environment able to react to Firebase’s events and use the SDK directly in the cloud. They extend Firebase functionalities with your custom code.
To use Cloud Functions follow these steps:
- Run
npm install -g firebase-tools
- Run
firebase
login to log in via the browser and authenticate the Firebase tool - Run
firebase init functions
- Choose TypeScript as a language
That’s it. Now you’re ready to write your first Function. To make this work, first you need to replace functions/index.ts with below code:
import * as functions from "firebase-functions"; import * as admin from "firebase-admin"; import { UserRecord } from "firebase-functions/lib/providers/auth"; admin.initializeApp(); const db = admin.firestore(); export const addNewUserToFirestore = functions.auth .user() .onCreate(async (user:UserRecord):Promise<FirebaseFirestore.WriteResult> => { const {displayName, uid, photoURL, email, emailVerified} = user; const newUser = db.collection('users').doc(uid); return await newUser.create({ displayName, photoURL, email, emailVerified }); });
This snippet allows us to import required modules and types, initialize the app, and more importantly get access to the Firestore database and export a new Cloud Function.
The Function uses the user.create trigger
to be activated whenever a new user is added. The functions.auth.user().onCreate
method takes an async function in form of a parameter and invokes it when necessary. Full documentation can be checked under the link here: Firebase Authentication triggers (google.com)
In the invoked function we destructurize the user
object and create a new user in the database.
Now deploy your Function with firebase deploy --only functions
. It can be viewed in the Console in the Functions section after all.
From now on, whenever a new user logs in to our application we will be able to collect data about him in the Firestore. Just as simple as that!
Summary
As you can see you can quickly implement some functionalities in Firebase, while possessing almost no code. It serves as a backend-as-a-service and allows for extending it with Cloud Functions.
It is also worth noting that the Firebase SDK uses WebSockets for providing real-time functionalities. You can directly subscribe to the Firestore database in your JS/TS code and response to any changes in data in real time. Don’t forget that you can also use Firebase for notifications amongst many other things.
I hope you found our article pleasant, and more importantly, helpful on your way to become Firebase-expert. If you’re on Fire after this short tutorial, then we’re glad and always happy to help!
Check out other articles in the technology bites category
Discover tips on how to make better use of technology in projects