Analytica House
May 24, 2024Write e-commerce Purchases to Firestore with sGTM
Server-side Google Tag Manager (sGTM) offers enhanced flexibility and security for tracking and handling data in your e-commerce applications. One powerful application of sGTM is writing purchase data directly to Firestore, Google Cloud's NoSQL database.
This blog post will walk you through the process of setting up sGTM to capture e-commerce purchases and store them in Firestore.
Step 1: Creating a New Server-side Google Tag Manager (sGTM) Template
In this step, you'll create a custom template in your server-side Google Tag Manager (sGTM) container. This template will define the logic for capturing e-commerce purchase events and sending the data to Firestore. By creating a reusable template, you streamline the process of handling and managing purchase data across your e-commerce platform.

You can use this code to accessing write and read data to Firestore from sGTM.
const Firestore = require('Firestore');
const Object = require("Object");
const getTimestampMillis = require("getTimestampMillis");
let writeData = {
timestamp: getTimestampMillis()
};
if (data.customData && data.customData.length) {
for (let i = 0; i < data.customData.length; i += 1) {
const elem = data.customData[i];
if (elem.fieldValue) {
writeData[elem.fieldName] = elem.fieldValue;
} else {
Object.delete(writeData, elem.fieldName);
}
}
}
const rows = writeData;
Firestore.write('', rows, {
projectId: '',
merge: true,
}).then((id) => {
data.gtmOnSuccess();
}, data.gtmOnFailure);
Step 2: Configuring the Firestore Database
- Open Google Cloud Console: Navigate to the Firestore section.

-
Create Database: Follow the prompts to set up a Firestore database in "production mode" or "test mode" based on your requirements.

You may also create a new rule like this while you are running test mode:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Now you can send the any purchase data to Firestore like this:

Contact us for more use cases using server-side Google Tag Manager.
More resources
Detect Performance Drops Early with Anomaly Detection
In digital products, the most critical problems are often the ones noticed the latest. Traffic drops...
How to Identify Non-Indexed Pages?
If you manage a website or monitor SEO processes, you know that the foundation of your digital prese...
How Do 404, 410, and 401 Status Codes Affect SEO?
In the digital world, the technical health of your website is one of the most fundamental factors de...