Node.js and Firebase Tutorial

Firebase is a powerful backend-as-a-service platform that provides various services to build real-time web and mobile applications.

In this tutorial, you will learn to work with the Firebase with Node.js.

Setting Up Firebase in Node.js

  1. To get started, you'll need to install the Firebase Admin SDK
  2. npm install firebase-admin
        
  3. Initialize Firebase in your Node.js application using your Firebase project credentials.
  4. const admin = require('firebase-admin');
    const serviceAccount = require('path/to/your/serviceAccountKey.json');
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: 'https://your-database-url.firebaseio.com',
    });
    

Realtime Database

  1. Firebase Realtime Database is a NoSQL database that provides real-time synchronization.
  2. You can read and write data to the database.
const db = admin.database();
const ref = db.ref('sampleData');

// Writing data
ref.set({ name: 'Alice', age: 25 });

// Reading data
ref.once('value', (snapshot) => {
    console.log('Data:', snapshot.val());
});
    

Authentication

  1. Firebase Authentication offers user authentication for your app.
  2. You can sign up, sign in, and manage users.
const auth = admin.auth();
// Creating a new user
auth.createUser({
    email: 'user@example.com',
    password: 'password123',
})
    .then((userRecord) => {
    console.log('User created:', userRecord.uid);
    })
    .catch((error) => {
    console.error('Error creating user:', error);
    });

// Signing in with email and password
auth.signInWithEmailAndPassword('user@example.com', 'password123')
    .then((userCredential) => {
    console.log('User signed in:', userCredential.user.uid);
    })
    .catch((error) => {
    console.error('Error signing in:', error);
});
    

Cloud Firestore

  1. Cloud Firestore is a NoSQL database that provides more advanced querying capabilities compared to the Realtime Database.
const db = admin.firestore();
    const usersCollection = db.collection('users');

    // Adding a document
    usersCollection.add({ name: 'Bob', age: 30 });

    // Querying data
    usersCollection.where('age', '>', 25)
    .get()
    .then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log('Document data:', doc.data());
    });
});
    

Cloud Functions

  1. Firebase Cloud Functions allow you to run backend code in response to various events in Firebase services.
const functions = require('firebase-functions');

exports.myFunction = functions.https.onRequest((request, response) => {
    response.send('Hello from Firebase Cloud Functions!');
});
    

Firebase Storage

  1. Firebase Storage enables you to store and serve user-generated content, such as images and videos.
const storage = admin.storage();
const bucket = storage.bucket('your-storage-bucket.appspot.com');

// Uploading a file
bucket.upload('local-file.jpg', {
    destination: 'images/image.jpg',
});

// Downloading a file
bucket.file('images/image.jpg').download((err, contents) => {
    console.log('File content:', contents);
});
    

Error Handling

  1. Always handle errors when working with Firebase services to ensure robust applications.
auth.signInWithEmailAndPassword('user@example.com', 'invalid-password')
.then((userCredential) => {
    console.log('User signed in:', userCredential.user.uid);
})
.catch((error) => {
    console.error('Error signing in:', error.message);
});