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
What Is GEO Consulting? The Era of Generative Engine Optimization
Digital marketing is experiencing its most profound shift since the dawn of the commercial internet....
What Is SEO Consulting? What Does SEO Consulting Entail?
In today’s digital environment, visibility is the primary measure of success. As search engine algor...
What is Cohort Analysis? Understanding User Behaviors through Segmentation
In the world of digital marketing and product management, making data-driven decisions is no longer...