Custom Server-Side GTM Client
An enterprise sGTM Client transforming Server-Side Tag Manager into a universal data gateway capable of routing any HTTP telemetry payload to advertising and analytics APIs.
Core Code Architecture:
sGTM Client Request Handler const claimRequest = require('claimRequest');
const getRequestPath = require('getRequestPath');
const getRequestBody = require('getRequestBody');
const runContainer = require('runContainer');
const setResponseBody = require('setResponseBody');
const setResponseStatus = require('setResponseStatus');
if (getRequestPath() === '/api/v1/telemetry') {
claimRequest();
const body = JSON.parse(getRequestBody() || '{}');
const eventData = {
event_name: body.event,
client_id: body.user_id || 'anonymous',
user_data: {
email: body.email,
phone: body.phone
},
value: body.value,
currency: body.currency || 'USD'
};
runContainer(eventData, () => {
setResponseStatus(200);
setResponseBody(JSON.stringify({ status: 'success', processed: true }));
});
}
Why the Native GA4 Client is Insufficient
Server-Side GTM is architected around a Client-Container-Tag pattern. While the default GA4 Client handles incoming /g/collect hits from gtag.js, modern architectures require processing server-to-server webhooks (e.g. Stripe payment confirmations, CRM lead qualification changes, mobile app backend events). Without a custom Client, these requests return 404 or cannot populate the sGTM Common Event Model.
- Intercept non-standard HTTP JSON payloads on custom paths (e.g. /events/webhook)
- Validate authorization tokens and request signatures before container execution
- Map arbitrary JSON schemas directly into sGTM standardized event parameters
System Architecture & Request Lifecycle
Incoming POST requests are inspected, claimed, normalized into the Common Event Model, and dispatched in parallel to server-side tags.
Security, Rate-Limiting & Error Protocols
The Client includes enterprise security protocols preventing malicious injection and excessive cloud compute charges.
- Bearer Token Authentication: Rejects unauthorized requests with 401 Unauthorized before invoking tags
- Payload Size Limiter: Drops payloads exceeding 64KB to safeguard Cloud Run CPU resources
- Response Headers: Injects CORS policies and returns structured JSON acknowledgments
- Try/Catch Sanitization: Prevents container-level crashes upon receiving malformed JSON