How to backup Firestore using firebase cloud functions

How to backup Firestore using firebase cloud functions

In this article, we will cover how to backup your firestore data periodically using firebase cloud functions

ยท

2 min read

The main reason for data backup is to save important files if a system crashes or somebody deletes the whole database by mistake ๐Ÿฅฒ

Lets get started...

Please ensure that you have enabled billing in your current firebase project before continuing.

Step 1 - Create a cloud storage bucket

bucket.png

  • GIve your storage bucket a unique name and then copy it after successfully creating the bucket, we will use it later.

Step 2 - Create a cloud function

  • Copy the cloud function below
const functions = require('firebase-functions');
const firestore = require('@google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();

// Replace BUCKET_NAME
const bucket = 'gs://BUCKET_NAME';

exports.scheduledFirestoreExport = functions.pubsub
                                            .schedule('every 24 hours')
                                            .onRun((context) => {

  const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT;
  const databaseName = 
    client.databasePath(projectId, '(default)');

  return client.exportDocuments({
    name: databaseName,
    outputUriPrefix: bucket,
    // Leave collectionIds empty to export all collections
    // or set to a list of collection IDs to export,
    // collectionIds: ['users', 'posts']
    collectionIds: []
    })
  .then(responses => {
    const response = responses[0];
    console.log(`Operation Name: ${response['name']}`);
  })
  .catch(err => {
    console.error(err);
    throw new Error('Export operation failed');
  });
});

Replace only the BUCKET_NAME variable with your storage bucket name that you just copied

GCP_PROJECT and GCLOUD_PROJECT will be preconfigured automatically after deploying our function

This cloud function will be responsible for backing up our firestore data every 24 hours to the bucket we just created.

  • Deploy the scheduled function
    firebase deploy --only functions
    

Final step - Configuring access permissions

We need give the Cloud Function that we just created permission to start export operations and to write to the storage bucket that we created above. We will use cloud shell to to configure the permission

gcloud projects add-iam-policy-binding PROJECT_ID \
    --member serviceAccount:PROJECT_ID@appspot.gserviceaccount.com \
    --role roles/datastore.importExportAdmin
gsutil iam ch serviceAccount:PROJECT_ID@appspot.gserviceaccount.com:admin \
    gs://BUCKET_NAME

NB// Please replace the PROJECT_ID AND BUCKET_NAME in the code above

You can get the PROJECT_ID from your project settings in the firebase console

The BUCKET_NAME is the name of the bucket you copied above

Congratulations ๐ŸŽ‰ You have successfully backed up your firestore data

ย