How to Auto-Translate Firestore Documents with Firebase Extension

Firebase

Sep 15, 2023

Introduction

Integrating multilingual support into applications is crucial for reaching a global audience, and the Firebase ecosystem provides an elegant solution for this challenge. The Translate Text in Firestore extension harnesses the capabilities of Google Cloud’s Translation API to automatically translate strings within a Cloud Firestore collection into various languages.

This article will guide you through setting up and using the “Translate Text in Firestore” extension to add multi-language support to your Firebase application.

Google Cloud Translation

Cloud Translation is a service by Google that allows for text translation across websites and applications through an API. Utilizing a powerful Neural Machine Translation (NMT) model.

Benefits:

  • Extensive Language Support: It supports translation for over 100 languages.
  • Scalability: The service scales with your needs, offering unlimited character translation.
  • Auto Language Detection: Cloud Translation can identify if the source text’s language is unknown.
  • Controlled Budgeting: You can set quota limits to manage costs effectively.

For more details, please refer to the Translation API docs page.

Getting Started

The first step in leveraging the Firestore translation extension is to have a Firebase project ready. If you haven’t already, follow the instructions to:

Once your project is prepared, you can add the translation extension to your application.

Extension Installation

You can install the “Translate Text in Firestore” extension: the Firebase Console or the Firebase CLI.

Option 1: Firebase Console

Navigate to the Firebase Extension’s page and find the “Translate Text in Firestore” extension. Click on “Install in Firebase Console” and follow the prompts to set your configuration parameters.

Install translate text in Firestore via Firebase console

Option 2: Firebase CLI

Alternatively, you can install the extension via the Firebase CLI with the following command:

firebase ext:install firebase/firestore-translate-text --project=your_project_id

Configure Translation Extension

Configuration parameters are essential in customizing the “Translate Text in Firestore” extension.

Translate text in Firestore Firebase Extensions parameters

Here’s what you can set up:

  • Target Languages: For instance, if you aim to translate strings into English, Spanish, German, and French, you would provide a list like en,es,de,fr. View the complete list of supported languages.
  • Collection Path: This is the location within your Firestore database where the texts to be translated are stored. An example is users/{userId}/messages.
  • Input Field Name: The specific field in your documents that contains the original text. For example, if your messages are stored under the field text, you would specify this.
  • Translations Output Field Name: The field where the translated strings will be stored. For example, you might call it translated.
  • Languages Field Name: If you have a dynamic language setting per document, you might use a field called preferred_languages. If this isn’t set, the extension uses the default target languages you’ve provided.
  • Translate Existing Documents?: If you enable this, all existing documents under the collection path will be processed. For instance, if you add Italian (‘it’) to your target languages later, enabling this option will backfill the Italian translation for existing documents.

Translation Workflow

After installing and configuring the extension, it automatically monitors the specified Firestore collection for changes. Here’s what happens behind the scenes:

  1. Document Creation/Update: When a new document with a specified input field is created or an existing one is updated, the extension detects this change.
  2. Translation Process: The extension calls the Google Cloud Translation API, translating the string from the input field into the specified languages.
  3. Storage of Translations: Translated strings are then stored in the output field within the same document in Firestore, often structured as a map or subcollection, with language codes as keys.

Translate text in Firestore Firebase Extensions parameters

Steps to Add Translations to Firestore Documents

Before initiating your operations, verify that the Firebase SDK is properly initialized and that you have the necessary permissions to interact with Firestore. You may want to store data in a user collection in many applications. To facilitate this, you can configure Firebase auth to handle user authentication. You can retrieve and utilize the userId for data operations upon successful authentication.

const firebaseConfig = {
  // Your Firebase configuration keys
};

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();

let userId;

auth.onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, set the userId
    const userId = user.uid;
  }
});

Step 1: Write the Input String to Firestore

You’ll start by adding a string to the Firestore document you want to translate. The input can be a single string or a map of strings if you have multiple texts to translate.

Example for a Single String Input

const messageRef = db.collection('users/{userId}/messages').doc('messageId');

messageRef.set({
  text: 'My name is Bob', // Your input string
});

Note: Replace {userId} with the actual user ID .

When you write this string to the text field of your document, the Firestore Translate Text extension will automatically detect the source language and create translations in the specified target languages.

Example for a Map of Input Strings

const messageRef = db.collection('users/{userId}/messages').doc('messageId');

messageRef.set({
  text: {
    first: 'My name is Bob',
    second: 'Hello, friend',
  },
});

In this example, the text field is a map containing multiple strings that you want to translate.

Step 2: Verify the Translated Output in Firestore

After the Firestore Translate Text extension processes the input string(s), you can check the translated field in your document for the output.

Example Output for a Single String Input

{
  "text": "My name is Bob",
  "translated": {
    "de": "Ich heiße Bob",
    "en": "My name is Bob",
    "es": "Mi nombre es Bob",
    "fr": "Je m'appelle Bob"
  }
}

Example Output for a Map of Input Strings

{
  "text": {
    "first": "My name is Bob",
    "second": "Hello, friend"
  },
  "translated": {
    "first": {
      "de": "Ich heiße Bob",
      "en": "My name is Bob",
      "es": "Mi nombre es Bob",
      "fr": "Je m'appelle Bob"
    },
    "second": {
      "de": "Hallo Freund",
      "en": "Hello, friend",
      "es": "Hola amigo",
      "fr": "Salut l'ami"
    }
  }
}

The Firestore Translate Text extension will update the translations automatically whenever the text field of the document is updated.

Translate text in Firestore Firebase Extensions parameters

Step 3: Use the Translations in Your Application

Now that the translations are available in your Firestore document, you can fetch and use them in your application.

Remember to replace {userId} with the actual ID of the user and messageId with the identifier of the specific message you want to translate.

To listen for real-time updates to your Firestore document and display the translations on a web application, you can use Firebase’s onSnapshot method. Here’s how you can implement it:

Steps to Listen for Real-Time Updates and Display Translations

Create a function that sets up a listener on the specific Firestore document. The onSnapshot method will invoke a callback function every time the document is updated, including the initial state.

function listenForTranslations(userId, messageId) {
  const messageRef = db
    .collection('users')
    .doc(userId)
    .collection('messages')
    .doc(messageId);

  messageRef.onSnapshot(
    (doc) => {
      if (doc.exists) {
        const data = doc.data();

        if (data.translated) {
          console.log(data.translated); // You can now update your UI
        }
      } else {
        console.error('Document does not exist!');
      }
    },
    (error) => {
      console.error('Error listening to document changes:', error);
    }
  );
}

Invoke the function listenForTranslations with the correct userId and messageId when the web page loads or it’s appropriate within your application’s lifecycle.

// Example call
listenForTranslations('exampleUserId', 'exampleMessageId');

Steps to Retrieve and Display Translated Text from Firestore

Define the Collection Path

Based on the provided example, set the path to the collection that holds the documents with the text to be translated. In this case, it’s a subcollection under each user:

const messagesRef = db.collection(`/users/{userId}/messages`);

Create a Function to Display Translations

Define a function that retrieves and logs the translation for a specified document and language code.

function displayTranslation(userId, docID, languageCode) {
  // Reference to a specific user's messages document
  const docRef = db.collection(`/users/${userId}/messages`).doc(docID);
  // Get the document
  docRef
    .get()
    .then((doc) => {
      if (doc.exists) {
        // 'translations' is the field where the translated texts are stored
        const translations = doc.data().translations;
        // Log the translation for the specified language
        console.log(translations[languageCode]);
      } else {
        console.log('No such document!');
      }
    })
    .catch((error) => {
      console.log('Error getting document:', error);
    });
}

Call the Function with Specific Parameters

To use the function, call it with the appropriate user ID, document ID, and language code.

// Example call
displayTranslation('user123', 'message456', 'es');
// To display the Spanish translation of a specific message

In this example, user123 is the ID of the user whose messages you want to access, message456 is the ID of the specific message document, and es is the ISO-639-1 code for Spanish, indicating that you want to retrieve the Spanish translation of the message.

Following these steps, you can effectively retrieve and display translations for documents stored in Firestore based on the setup provided by the Firestore Translation extension configuration.

Text Translator app powered by Firebase Translate Text in Firestore

Conclusion

The “Translate Text in Firestore” Firebase Extension simplifies creating a multilingual experience in your web or mobile applications. By automating the translation of text strings in Firestore, this extension supports instant global reach, enabling your app to communicate with users in their native languages and thus enhance user engagement and satisfaction.

Incorporate the “Translate Text in Firestore” extension into your Firebase application today to break down language barriers and open your app to a broader audience.