Firebase is a really great backend tool which works very well with mobile apps and web apps as well.
Firebase allows you interact with cloud database and write backend api function using javascript. So if you are a frontend javascript developer, using firebase you are able to easily write backend code in your application.
At first we are not easily convinced about Firebase, but after using it in action it seems like Firebase may be able to speed up conventional mobile and web app development — by a lot!
Firebase aims to solve all of this and make your backend truly minimal maintenance, taking things a step further than any other product I’ve seen.
What is Firebase
Firebase is a backend platform for building Web, Android and IOS applications. It offers real time database, different APIs, multiple authentication types and hosting platform. This is an introductory tutorial which covers the basics of the Firebase platform and explains how to deal with its various components and sub-components.Its also allow us to use the seamless connection between user and data with authentication provided by firebase.
Why Firebase + React Native
Fast development. Very fast development !
Here’s what you’ll learn in this Blog:
- Configuration of project backend.
- Authentication with firebase.
- Basic Write Operation with firebase.
- Reading data from firebase.
- Storing the data in the realtime database.
Environment Setup: Your Backend
First you need to create a project account on firebase console so that we can use that project config in App later on. Click Here and then click “Go to Console” in the top right.
Write your project name set your region and firebase will create your Project-ID.
After that it firebase will ask to select your base of project of android, iOS or website.
Select your project (web app) and create new for it, Then Next, go to the Authentication tab > Sign in method tab and enable Sign in method as your Sign-in provider(s).
Click on add Firebase as webApp will show the page copy config will be using at the end of fronted setup.
This all for backend setup, now we will move forward to setup our Front-end that require react native environment setup already .
React native is just an example in the current case, we can use this in any web app as well.
React-Native front end configuration
To demonstrate firebase, we will setup a very simple app in which will setup login/registration for a user and also allow the user his set this name into a cloud database.
Create a new project will take time, Meanwhile you can have cup of coffee 🙂 !!
$ react-native init firebaseproject
Install Firebase module with Npm.
$ npm install --save firebase
Now open up your project in favorite CodeEditor.
Setting up Login/Sign-up
Create a new file with which will contain configuration file of firebase. Where we are going to initialise our app , also never forget to import the module from node module as we I have did in first line.
import * as firebase from "firebase"; var config = { apiKey: "you Api key", authDomain: "Your auth domain", databaseURL: "https://Your project database Url", projectId: "myfirstfirebaseproject-abf19", storageBucket: "myfirstfirebaseproject", messagingSenderId: "926600885980" }; firebase.initializeApp(config);
Now the signup flow.
signup(email, pass) { try { await firebase.auth() .createUserWithEmailAndPassword(email, pass); console.log("Account created"); // Navigate to the Home page, the user is auto logged in } catch (error) { console.log(error.toString()) } }
Most of the firebase functions are promised based, but using async/await makes this a lot easier.
On the place to console.log(“Account Created”) you can also use a callback in order to update values in your component or simply use a return statement.
Here we can see a user is added to our Firebase app
Now will create a login function similar to sign up.
login(email, pass) { try { await firebase.auth() .signInWithEmailAndPassword(email, pass); console.log("Logged In!"); // Navigate to the Home page } catch (error) { console.log(error.toString()) } }
Same with logout function
logout() { try { await firebase.auth().signOut(); // Navigate to login view } catch (error) { console.log(error); } }
Storing the data in the realtime database
What we saw above, is authentication in firebase. Now let’s see about firebase cloud DB.
Key Concept for firebase database
JSON Tree
Let start with Real-Time Database form which we are already familiar, they store their data as JSON objects. But in firebase when you add data to the JSON tree, it becomes a node in the existing JSON structure with anUnique key
The best part about Unique keys is, you can set these according to your choices like User ID or semantic names, it all up to you.
For example, consider a contact application that allows users to store a basic phone contact and profile. We can store a particular user information as below we have saved for Mohit. Here we are using the key as person name.
{ "profile": { "Mohit": { "name": "Mohit Kumar", "contacts": { "phonenumber": "7838912911" }, }, "Rohit": { ... }, "Ashok": { ... } } }
Avoid nesting data
Firebase allows us up to 32 level of nesting data, which doesn’t mean that you should always use nesting, as when you give permission to user for reading and write access of node in the database, you also grant them access to the all current data present in a node.
So the best way is to keep database structure as flat as possible.
import * as firebase from "firebase"; class Database { /** * @param Set User Name. * @param userId */ static setUserName(userId) { let userNamePath = "/user/" + userId + "/details"; return firebase.database().ref(userNamePath).set({ userName: userName }) } /** * @param Delete UserName. * @param userId */ static deleteUserName(userId) { // User Details will be deleted let userNamePath ="/user/" + userId + "/details"; retrun deleteuserNamePath } /** * Listen for changes to a users name number * @param userId * @param callback Users name */ static listenToUser(userId, callback) { let userNamePath = "/user/" + userId + "/details"; firebase.database().ref(userNamePath).on('value', (snapshot) => { var userName = ""; if (snapshot.val()) { userName = snapshot.val().userName } callback(mobile) }); } } module.exports = Database;
The above setUserName function will help a user to set username in a real-time database, and listenToUser function let you have the updated list of added username from the DB.
**Use of database function in react component **
class DatabaseFunctionCall extends Component { constrcutor(props) { super(props); } componentDidMount() { try { Database.setUserName(userId, snapShot => { // Here you see the snapShot values. // User can fire other qurey here. }); } catch (error) { // Can log error in console console.log(error); } } }
Authorizing Access to the Data
Access to data with authorization is the biggest concern for a developer because if you haven’t set any security rules for firebase database, Anyone can perform read and write action in your database.
You can find these rules in database table section, have a look to below image.
In initial setup of database, auth rules are set to null, you can modify this accroding to requirement.
{ "rules": { ".read": "auth != null", ".write": "auth != null" } }
See the docs for more information of authentication on the Realtime Database here
Above we have seen basics of using firebase