BREAKING:

Firebase Runtime Sync (Shadow Migrate)

Here is the step-by-step guide to setting up automatic synchronization from Project A (Source) to Project B (Destination) using Cloud Functions.

Step 1: Prerequisites

  1. Install Node.js: Download it from the Node.js Official Website.
  2. Install Firebase CLI: Open your terminal and run: npm install -g firebase-tools
  3. Login: Run firebase login and follow the instructions in your browser.

Step 2: Get the “Key” for Project B (Destination)

Project A needs permission to write to Project B.

  1. Go to the Firebase Console and open Project B.
  2. Click the Gear icon (⚙️) > Project Settings.
  3. Go to the Service Accounts tab.
  4. Click Generate new private key, download the .json file, and rename it to dest-service-account.json.

Step 3: Initialize Project A (Source) Locally

  1. Create a folder on your computer (e.g., firebase-sync).
  2. Open your terminal inside that folder and run: firebase init functions
  3. Follow these prompts:
    • Project Setup: Select Use an existing project and pick Project A.
    • Language: Select JavaScript.
    • ESLint: Type n.
    • Install dependencies: Type y.
  4. Copy the dest-service-account.json file (from Step 2) into the newly created functions folder.

Step 4: Add the Script

Open functions/index.js and replace the content with this code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

// Initialize Project A (Source) automatically
admin.initializeApp();

// Initialize Project B (Destination) using the key file
const destApp = admin.initializeApp({
  credential: admin.credential.cert(require('./dest-service-account.json'))
}, 'destination');

const destDb = destApp.firestore();

// Trigger: Watch for changes in Project A's "users" collection
exports.syncToDest = functions.firestore
  .document('users/{userId}') 
  .onWrite(async (change, context) => {
    const userId = context.params.userId;
    const destRef = destDb.collection('users').doc(userId);

    // If deleted in Source -> Delete in Destination
    if (!change.after.exists) {
      return destRef.delete();
    }

    // If created/updated in Source -> Sync to Destination
    const newData = change.after.data();
    return destRef.set(newData, { merge: true });
  });

Step 5: Upgrade to Blaze Plan

To communicate between two different Firebase projects, Project A must be on the Blaze Plan (Pay-as-you-go).

  • You can upgrade via the Firebase Console Billing section.
  • Note: There is a generous free tier, so small-scale syncing usually costs $0.

Step 6: Deploy

In your terminal, inside the root folder, run:

firebase deploy --only functions

========================================================
Deploy with the JSON service account:
========================================================
Chuẩn bị: Để file JSON vào thư mục dự án của bạn (ví dụ đặt tên là service-account.json).

Thiết lập biến môi trường:

  • macOS / Linux: export GOOGLE_APPLICATION_CREDENTIALS="đường/dẫn/đến/service-account.json"
  • Windows (PowerShell): $env:GOOGLE_APPLICATION_CREDENTIALS="đường/dẫn/đến/service-account.json"

Kiểm tra project: Đảm bảo bạn đang trỏ đúng vào Project ID trong file JSON (abc-ai-app):

firebase use abc-ai-app

Deploy:

firebase deploy --only functions

Post A Comment

Your email address will not be published. Required fields are marked *

Leave a Reply