0% found this document useful (0 votes)
9 views8 pages

Firebase Basics for Beginners

The document provides a comprehensive tutorial on getting started with Firebase Console, including creating a project, accessing the Realtime Database, configuring authentication, and performing basic CRUD operations. It explains the structure of data in JSON format and how to implement Firebase security rules. Additionally, it covers the Firebase SDK for integrating various services into applications, along with examples for writing and reading data.

Uploaded by

Thanh Pham Minh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views8 pages

Firebase Basics for Beginners

The document provides a comprehensive tutorial on getting started with Firebase Console, including creating a project, accessing the Realtime Database, configuring authentication, and performing basic CRUD operations. It explains the structure of data in JSON format and how to implement Firebase security rules. Additionally, it covers the Firebase SDK for integrating various services into applications, along with examples for writing and reading data.

Uploaded by

Thanh Pham Minh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Beginner Print

Getting Started with Firebase Console Tutorial


Getting Started with Firebase Console involves creating a Firebase project and navigating through the
Firebase Console interface to access various Firebase services. This is the first step in building
applications that utilize Firebase's powerful backend capabilities. Users can create and manage
databases, configure authentication, set up hosting, and monitor application usage all from the Firebase
Console.
Copy
Create a Firebase Project
1. Go to the Firebase Console at https://console.firebase.google.com/
2. Click 'Add project'.
3. Enter a name for your project and click 'Continue'.
4. (Optional) Configure Google Analytics for this project and click 'Continue'.
5. Click 'Create project', then 'Continue' when the project is created.

Accessing Firebase Realtime Database


1. In the Firebase Console, select your project.
2. Click on 'Realtime Database' from the left sidebar.
3. Click 'Create Database'.
4. Choose 'Start in Test Mode' or 'Start in Locked Mode' based on your preference, then
click 'Next' and 'Done'.

Configuring Authentication
1. In the Firebase Console, select your project.
2. Click on 'Authentication' in the left sidebar.
3. Click 'Get Started'.
4. Go to the 'Sign-in method' tab.
5. Choose the authentication methods you want to enable (e.g., Email/Password, Google).
6. Click 'Save' after enabling any necessary methods.

Creating a Firebase Realtime Database Tutorial


Creating a Firebase Realtime Database involves setting up a Firebase project and enabling the Realtime
Database service. This process allows you to store and synchronize data in real-time, making it
accessible across multiple clients. The database structure is JSON-based, and data can be manipulated
through the Firebase SDK, enabling developers to build dynamic applications that require instant data
updates.
Copy
Initialize Firebase and Create Database Reference
import firebase from 'firebase/app';
import 'firebase/database';

// Your web app's Firebase configuration


const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_PROJECT_ID.firebaseapp.com',
databaseURL: 'https://YOUR_PROJECT_ID.firebaseio.com',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_PROJECT_ID.appspot.com',
messagingSenderId: 'YOUR_SENDER_ID',
appId: 'YOUR_APP_ID'
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Get a reference to the database


const database = firebase.database();

Creating Data in Realtime Database


const userRef = database.ref('users/');

// Adding a new user


userRef.set({
userId: '1',
name: 'John Doe',
email: '[email protected]'
});

Retrieving Data from Realtime Database


userRef.on('value', (snapshot) => {
const data = snapshot.val();
console.log(data);
});

Adding Firebase to a Web App Tutorial


Adding Firebase to a web application involves initializing Firebase in your app, configuring it with your
project's unique credentials, and then integrating the necessary Firebase services for your application's
functionality. This process typically begins by including the Firebase SDK in your HTML file or through a
package manager, followed by initializing Firebase with your project's configuration settings obtained
from the Firebase console.
Copy
Including Firebase SDK via script tags
<script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js"></script>

Initializing Firebase in your app


const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
Accessing Firebase Realtime Database
const database = firebase.database();

// Example of writing data to the database


database.ref('path/to/data').set({
username: "exampleUser",
email: "[email protected]"
});

Basic CRUD Operations: Create, Read, Update, Delete Tutorial


Basic CRUD operations are essential for managing data in a Firebase Realtime Database. CRUD stands
for Create, Read, Update, and Delete, which are the four basic functions for manipulating data. In the
context of Firebase, these operations allow developers to add new data, retrieve existing data, modify
data, and remove data from the database in real-time. This subtopic will cover the fundamental
methods provided by the Firebase SDK to interact with the database effectively.
Copy
Create Data
firebase.database().ref('users/').push({ name: 'John Doe', age: 30 });

Read Data
firebase.database().ref('users/').on('value', (snapshot) => { const users = snapshot.val();
console.log(users); });

Update Data
firebase.database().ref('users/userId').update({ age: 31 });

Delete Data
firebase.database().ref('users/userId').remove();

Understanding Data Structure: JSON Format Tutorial


In Firebase Realtime Database, data is structured in a JSON format, where data is organized as key-
value pairs in a hierarchical format. This means that data can be nested, allowing developers to create
complex data structures that are intuitive and easy to navigate. Understanding how to effectively
structure data in JSON is crucial for optimizing data retrieval, ensuring data integrity, and building
scalable applications.
Copy
Simple User Data Structure
{
"users": {
"user1": {
"name": "John Doe",
"email": "[email protected]",
"age": 30
},
"user2": {
"name": "Jane Smith",
"email": "[email protected]",
"age": 25
}
}
}

Nested Data Structure for a Chat Application


{
"messages": {
"message1": {
"sender": "user1",
"text": "Hello!",
"timestamp": 1635453456000
},
"message2": {
"sender": "user2",
"text": "Hi there!",
"timestamp": 1635453467000
}
}
}

Product Catalog Structure


{
"products": {
"product1": {
"name": "Laptop",
"price": 999.99,
"category": "Electronics"
},
"product2": {
"name": "Coffee Mug",
"price": 19.99,
"category": "Kitchen"
}
}
}

advertisement
Reading Data: On Value Listener Tutorial
The 'On Value Listener' in Firebase Realtime Database allows you to listen for changes to a specific
location in the database. Once added, the listener will trigger every time the data at that location is
modified, providing a real-time snapshot of the data. This is particularly useful for applications that
need to display live updates, such as chat applications or dashboards.
Copy
Basic On Value Listener
const dbRef = firebase.database().ref('path/to/data');

dbRef.on('value', (snapshot) => {


const data = snapshot.val();
console.log('Data received:', data);
});

On Value Listener with Error Handling


const dbRef = firebase.database().ref('path/to/data');
dbRef.on('value', (snapshot) => {
const data = snapshot.val();
console.log('Data received:', data);
}, (error) => {
console.error('Error retrieving data:', error);
});

Single Use On Value Listener


const dbRef = firebase.database().ref('path/to/data');

dbRef.once('value').then((snapshot) => {
const data = snapshot.val();
console.log('Single fetch data:', data);
});

Writing Data: Set and Update Methods Tutorial


In Firebase Realtime Database, writing data is primarily conducted using the 'set' and 'update' methods,
which allow you to create new data entries or update existing ones within the database. The 'set'
method writes data to a specified location, replacing any existing data, while the 'update' method allows
you to modify specific child properties without affecting other data at that location. Understanding the
differences and use cases for these methods is crucial for managing data effectively in your
applications.
Copy
Using Set Method
firebase.database().ref('users/user1').set({ name: 'John Doe', age: 30 });

Using Update Method


firebase.database().ref('users/user1').update({ age: 31 });

Setting Nested Data with Set


firebase.database().ref('users/user2/profile').set({ name: 'Jane Doe', age: 25 });

Updating Nested Data with Update


firebase.database().ref('users/user2/profile').update({ age: 26 });

Deleting Data: Remove Method Tutorial


The 'Remove' method in Firebase Realtime Database is used to delete data at a specific database
reference. This operation effectively removes the data and its children, if applicable, from the database,
ensuring that it is no longer accessible or retrievable. It is crucial to use this method carefully, as
deleted data cannot be recovered. Users can call this method on a reference pointing to the desired
node they want to delete, either by specifying a path directly or by using a reference variable.
Copy
Delete a specific child node
const dbRef = firebase.database().ref('users/userId');
dbRef.remove()
.then(() => {
console.log('User deleted successfully.');
})
.catch((error) => {
console.error('Delete failed: ' + error.message);
});

Delete an entire list of items


const itemsRef = firebase.database().ref('items');
itemsRef.remove()
.then(() => {
console.log('All items deleted successfully.');
})
.catch((error) => {
console.error('Delete failed: ' + error.message);
});

Delete a specific key in an array


const arrayRef = firebase.database().ref('arrayOfItems/1');
arrayRef.remove()
.then(() => {
console.log('Array item deleted successfully.');
})
.catch((error) => {
console.error('Delete failed: ' + error.message);
});

Firebase Security Rules Overview Tutorial


Firebase Security Rules define how your data is structured and who has access to it. They allow you to
secure your Firebase Realtime Database by specifying conditions under which users can read or write
data. By implementing security rules, you can prevent unauthorized access and ensure that your
database interactions align with your application's privacy requirements. Understanding and configuring
these rules is critical to maintaining the integrity and security of your data.
Copy
Allow Read and Write for Authenticated Users
rules_version = '2';
service firebase.database {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}

Allow Read for All Users but Write Only for Authenticated Users
rules_version = '2';
service firebase.database {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if request.auth != null;
}
}
}

Restrict Access Based on User ID


rules_version = '2';
service firebase.database {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
}
}

Understanding Firebase SDK Tutorial


The Firebase SDK (Software Development Kit) is a set of tools and libraries provided by Firebase that
allows developers to integrate various Firebase services into their applications. It provides a seamless
way to access the Firebase Realtime Database and other Firebase functionalities such as
authentication, storage, and messaging. The SDK is available for multiple platforms including
JavaScript, Android, and iOS, allowing developers to manage users, data, and events efficiently while
leveraging the advantages of Firebase's cloud infrastructure.
Copy
Initializing Firebase in a Web App
import firebase from 'firebase/app';
import 'firebase/database';

const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DATABASE_URL',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID'
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

Reading Data from Firebase Realtime Database


const database = firebase.database();
const ref = database.ref('users');

ref.on('value', (snapshot) => {


const data = snapshot.val();
console.log(data);
}, (error) => {
console.error('Error reading data:', error);
});

Writing Data to Firebase Realtime Database


const database = firebase.database();
const ref = database.ref('users');

ref.set({
username: 'exampleUser',
email: '[email protected]'
}).then(() => {
console.log('Data saved successfully!');
}).catch((error) => {
console.error('Error saving data:', error);
});

You might also like