What is firebase ? Explain Firebase tutorial with MEAN stack examples

 What is Firebase?

Firebase is a platform developed by Google that provides a set of tools and services for developing web and mobile applications. It simplifies backend development by offering services like real-time databases, authentication, hosting, cloud functions, and more, with a focus on reducing the need for server-side management and scaling infrastructure. Firebase offers both free and paid services, and it's widely used for building mobile and web applications quickly and efficiently.

Key Firebase features include:

  • Firebase Authentication: Provides easy-to-integrate user authentication methods (email/password, Google login, Facebook login, etc.).
  • Firebase Realtime Database: A NoSQL cloud database that supports real-time data syncing between clients.
  • Cloud Firestore: A flexible, scalable database for mobile, web, and server development.
  • Firebase Hosting: Fast and secure web hosting for static assets.
  • Firebase Cloud Functions: Backend code that runs in response to Firebase events (e.g., database changes, user authentication).
  • Firebase Cloud Storage: Object storage for files such as images, videos, and other media.

Integrating Firebase with the MEAN Stack

The MEAN stack consists of MongoDB, Express, Angular, and Node.js, and Firebase can be used to enhance this stack with features like authentication and real-time database management.

Here’s a step-by-step guide to integrating Firebase with the MEAN stack.


Step-by-Step Firebase Integration with the MEAN Stack

1. Setting Up Firebase

First, you need to create a Firebase project to get your Firebase credentials.

  1. Go to the Firebase Console.
  2. Create a new Firebase project.
  3. Under Project Settings, get your Firebase configuration details (API keys, project ID, etc.) for use in your app.
json
{ apiKey: "your-api-key", authDomain: "your-auth-domain", databaseURL: "your-database-url", projectId: "your-project-id", storageBucket: "your-storage-bucket", messagingSenderId: "your-sender-id", appId: "your-app-id" }

2. Setting Up the Backend with Express and Firebase Admin SDK

Next, we’ll configure the backend to interact with Firebase and MongoDB.

  1. Initialize the Node.js Project:
bash
mkdir mean-firebase-backend cd mean-firebase-backend npm init -y npm install express firebase-admin mongoose body-parser cors
  1. Configure Firebase in Node.js Backend:
  • Create server.js to set up the Express server and Firebase Admin SDK.
javascript
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const mongoose = require('mongoose'); const admin = require('firebase-admin'); const app = express(); // Firebase Admin SDK setup const serviceAccount = require('./path/to/your-firebase-adminsdk.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "your-database-url" }); // MongoDB setup mongoose.connect('mongodb://localhost:27017/meanFirebase', { useNewUrlParser: true, useUnifiedTopology: true }); // Middleware app.use(bodyParser.json()); app.use(cors()); // Routes app.get('/', (req, res) => { res.send('Welcome to MEAN Firebase App'); }); app.post('/addUser', (req, res) => { const { name, email } = req.body; // Firebase Authentication Example: Create a new user admin.auth().createUser({ email: email, password: "your-password", displayName: name, }) .then(userRecord => { // Save user info to MongoDB const newUser = new User({ name, email, firebaseUid: userRecord.uid }); newUser.save() .then(() => res.status(201).send('User added successfully')) .catch(err => res.status(500).send(err)); }) .catch(error => res.status(400).send(error)); }); // MongoDB User Model const User = mongoose.model('User', new mongoose.Schema({ name: String, email: String, firebaseUid: String })); // Start server const port = 3000; app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
  1. Start the Server:
bash
node server.js

3. Setting Up the Frontend with Angular and Firebase

Now, let's set up the frontend with Angular and Firebase. We'll use AngularFire, the official Firebase library for Angular.

  1. Create an Angular Project:
bash
ng new mean-firebase-frontend cd mean-firebase-frontend npm install firebase @angular/fire
  1. Configure Firebase in Angular:
  • Go to src/environments/environment.ts and add your Firebase credentials:
typescript
export const environment = { production: false, firebaseConfig: { apiKey: "your-api-key", authDomain: "your-auth-domain", databaseURL: "your-database-url", projectId: "your-project-id", storageBucket: "your-storage-bucket", messagingSenderId: "your-sender-id", appId: "your-app-id" } };
  1. Modify app.module.ts:

Import Firebase and AngularFire:

typescript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AngularFireModule } from '@angular/fire'; import { AngularFireAuthModule } from '@angular/fire/auth'; import { AppComponent } from './app.component'; import { environment } from '../environments/environment'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireAuthModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
  1. Create a Simple Authentication Service:

In src/app/api.service.ts, create a service for interacting with Firebase and the backend.

typescript
import { Injectable } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { private apiUrl = 'http://localhost:3000'; constructor(private afAuth: AngularFireAuth, private http: HttpClient) { } // Register a new user registerUser(email: string, password: string): Observable<any> { return this.http.post(`${this.apiUrl}/addUser`, { email, password }); } // Sign up using Firebase Authentication signUp(email: string, password: string) { return this.afAuth.createUserWithEmailAndPassword(email, password); } // Login using Firebase Authentication login(email: string, password: string) { return this.afAuth.signInWithEmailAndPassword(email, password); } // Log out logout() { return this.afAuth.signOut(); } }
  1. Use the Service in a Component:

In src/app/app.component.ts, add the login and registration functionality.

typescript
import { Component } from '@angular/core'; import { ApiService } from './api.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { email = ''; password = ''; constructor(private apiService: ApiService) {} register() { this.apiService.registerUser(this.email, this.password).subscribe(response => { console.log('User Registered:', response); }); } login() { this.apiService.login(this.email, this.password).then(user => { console.log('User Logged In:', user); }).catch(error => { console.error('Error logging in:', error); }); } }

In src/app/app.component.html, create the UI for user registration and login:

<div> <h2>Register</h2> <input [(ngModel)]="email" placeholder="Email" /> <input [(ngModel)]="password" placeholder="Password" type="password" /> <button (click)="register()">Register</button> <h2>Login</h2> <button (click)="login()">Login</button> </div>
  1. Start the Angular Application:
ng serve

Visit http://localhost:4200 in the browser, where you can register and log in users using Firebase.


Conclusion

By following this tutorial, you integrated Firebase with the MEAN stack to handle authentication, real-time data syncing, and more. The backend is powered by Node.js and Express, using Firebase Admin SDK for server-side authentication, while MongoDB is used for storing user data. The frontend Angular app connects to Firebase for authentication and interacts with the backend for saving data.

This setup is ideal for quickly building scalable and feature-rich web and mobile applications with Firebase’s real-time and cloud services.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics