
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

How Do You Dynamically Pass Your CRM Audiences to Advertising Channels?
How to Dynamically Sync CRM Audiences to Ad ChannelsSay goodbye to static lists and hello to living...

Back to School and Return to City Life: 2025 Trends and Consumer Behaviors
Back to School and Return to City Life: 2025 Trends and Consumer BehaviorsThe back-to-school period...

How Does Inventory Management Impact E-commerce Success During Back-to-School Season?
How Does Inventory Management Impact E-commerce Success During Back-to-School Season?The back-to-sch...