Before you start

  • Make sure you have installed Firebase CLI. You can do this by running npm install -g firebase-tools.
  • Firebase Project Initialized, if not, run firebase init and following the prompts to connect your local project to the Firebase project.

Get serviceAccountKey.json

Find Service Account Tab

  1. Go to the Firebase console:

    • Open your web and navigate to the Firebase Console.
    • Log in with your Google account if you’re not already logged in.
  2. Navigate to the Service Account Tab:

    • Choose the Firebase project for which you want to create a service account.
    • Click on the gear icon nect to ‘Project Overview’ to open the ‘Project settings’.
    • In the Project settings, go to the ‘Service accounts’ tab.

Generate New Private Key:

You’ll find an option to generate a new private key in the Firebase Admin SDK section of the Service Accounts tab.

image-20240102191045492

Click on ‘Generate new private key’, and a prompt will appear warning you to keep your private key secure and not to share it. Comfirm to proceed.

Once you confirm, a JSON file will be downloaded to your computer. This is your serviceAccountKey.json file. Store this file securely. It gives administrative access to your Firebase project, so it should never be shared or exposed publicly.

Firestore

Export Data from Firestore Emulator

  • Make sure your Firestore emulator is running
  • Use the firebase emulators: export [export_directory] command to export your data. This will save your emulator data (including Firestore data) to the specified directory.

Sample Script

A sample script that reads all collections in Firestore Emulator, and stores it into a JSON file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const fs = require('fs');
const admin = require('firebase-admin');
const firebaseConfig = require('../../../firebase.json');

// Initialize Firebase Admin SDK
admin.initializeApp({
projectId: 'xxxx-xxx', // Your Product ID
...firebaseConfig,
credential: admin.credential.applicationDefault(),
});

// Connect to Firestore Emulator
const db = admin.firestore();
db.settings({
host: 'localhost:8080', // Replace with your Firestore emulator host and port
ssl: false,
});

// Function to get all documents from a collection
async function getAllDocuments(collectionRef) {
const snapshot = await collectionRef.get();
const documents = {};
snapshot.forEach((doc) => {
documents[doc.id] = doc.data();
});
return documents;
}

// Function to read all collections and their documents
async function readAllCollections() {
const collections = {};
const collectionsSnapshot = await db.listCollections();
for (const collection of collectionsSnapshot) {
const documents = await getAllDocuments(collection);
collections[collection.id] = documents;
}
return collections;
}

// Function to save data to JSON file
function saveDataToFile(data) {
const exportDir = './export';

// Create export directory if it doesn't exist
if (!fs.existsSync(exportDir)) {
fs.mkdirSync(exportDir);
}

const filePath = `${exportDir}/firestoreData.json`;

fs.writeFile(filePath, JSON.stringify(data, null, 2), (err) => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('Data successfully written to file');
}
});
}

// Execute and save data
readAllCollections()
.then((data) => saveDataToFile(data))
.catch((err) => console.error('Error reading collections:', err));

Storage

Installation

Make sure you have installed the required dependencies:

1
npm install firebase-admin @google-could/storage

Uploading Files to Firebase Storage

Here’s an example script that demonstrates how to upload files:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const admin = require('firebase-admin');
const { Storage } = require('@google-cloud/storage');
const path = require('path');
const fs = require('fs');

// Initialize Firebase Admin
admin.initializeApp({
credential: admin.credential.cert(require('./path/to/serviceAccountKey.json')),
});

// Your Google Cloud Storage bucket name (can be found in Firebase Storage URL)
const bucketName = 'your-firebase-storage-bucket-name';

// Initialize Google Cloud Storage
const storage = new Storage();
const bucket = storage.bucket(bucketName);

// Function to upload file to Firebase Storage
async function uploadFile(filePath) {
const destination = path.basename(filePath); // Or specify your desired path in the bucket

// Uploads a local file to the bucket
await bucket.upload(filePath, {
destination,
public: true, // if you want the file to be publicly accessible, set this to true
metadata: {
cacheControl: 'public, max-age=31536000', // example metadata
},
});

console.log(`${filePath} uploaded to ${bucketName}/${destination}`);
}

// Example usage
const localFilePath = './path/to/local/file'; // Path to the file you want to upload
uploadFile(localFilePath)
.then(() => console.log('File uploaded successfully'))
.catch(err => console.error('Error uploading file:', err));