First Party Pixel Tracking with GTM Server-Side & GA4

Back to All Articles

Introduction

As third-party cookies phase out and browser privacy restrictions tighten, first-party tracking has become essential for maintaining accurate analytics and marketing attribution. Google Tag Manager Server-Side (sGTM) combined with GA4 provides a robust solution for first-party data collection that respects user privacy while maintaining data accuracy.

This guide walks through the complete architecture, setup, and implementation of a server-side tracking infrastructure — from DNS configuration to Facebook Conversions API integration.

Why Third-Party Cookies Are Dying

Safari — Intelligent Tracking Prevention (ITP)

Apple led the charge with ITP, progressively restricting tracking since 2017:

With ~18-20% global browser market share (over 30% on mobile in the US), Safari’s restrictions significantly impact analytics accuracy.

Firefox — Enhanced Tracking Protection (ETP)

Firefox introduced Total Cookie Protection (default since Firefox 103 in 2022), which confines every cookie to the site where it was created. A Facebook cookie on site-a.com cannot be read on site-b.com, effectively killing third-party cookie-based tracking.

Chrome — Privacy Sandbox

Google reversed its plan to fully deprecate third-party cookies in Chrome (announced July 2024), but the trend is unmistakable. Safari and Firefox already block them, ~30-40% of desktop users run ad blockers, and privacy regulations continue tightening. Server-side first-party tracking is the new baseline.

Server-Side vs. Client-Side Tagging

Key Differences:
AspectClient-SideServer-Side
Where tags executeUser’s browserYour server
Browser requestsOne per vendor (many)One (to your server)
Cookie mechanismJavaScript document.cookieHTTP Set-Cookie header
ITP impact7-day / 1-day capFull lifetime (HTTP-set, not capped)
Ad blocker resilienceLowHigh (first-party subdomain)
Data controlVendors collect freelyYou control what leaves your server
Page performanceMultiple heavy scriptsOne lightweight request
CostFreeServer infrastructure costs

Architecture Overview

The data flow for server-side tagging:

[Browser] → loads GTM Web Container
    |
    | GA4 sends data to https://data.yourdomain.com/g/collect
    | (instead of https://www.google-analytics.com/g/collect)
    v
[Custom Subdomain: data.yourdomain.com]
    | DNS CNAME → your sGTM server (Cloud Run)
    v
[GTM Server-Side Container]
    | GA4 Client parses request into event data
    |
    +--→ GA4 Tag → Google Analytics 4
    +--→ Facebook CAPI Tag → Facebook Conversions API
    +--→ Google Ads Tag → Google Ads
    |
    v
[Response with first-party Set-Cookie headers back to browser]

Step-by-Step Implementation

Step 1: Create a Server-Side GTM Container

  1. Go to tagmanager.google.com and log in
  2. Click “Create Container” (or Admin → “+”)
  3. Name it descriptively (e.g., “yourdomain.com - Server”)
  4. Select “Server” as the target platform
  5. Choose automatic provisioning via Google Cloud (recommended) or manual deployment
  6. Note your Container ID (GTM-XXXXXX) and the Container Config string from Admin → Container Settings

Step 2: Deploy the Server Container on Google Cloud Run

# Ensure gcloud CLI is installed and authenticated
gcloud services enable run.googleapis.com

# Deploy the production server
gcloud run deploy sgtm \
  --image gcr.io/cloud-tagging-10302018/gtm-cloud-image:stable \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated \
  --min-instances 1 \
  --set-env-vars CONTAINER_CONFIG=<your_config_string>

# Deploy a separate preview server (for GTM debug mode)
gcloud run deploy sgtm-preview \
  --image gcr.io/cloud-tagging-10302018/gtm-cloud-image:stable \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated \
  --min-instances 1 \
  --set-env-vars CONTAINER_CONFIG=<your_config_string>,RUN_AS_PREVIEW_SERVER=true

Alternative hosting: You can also deploy on Google App Engine, AWS (ECS/Fargate), or managed providers like Stape.io (~$20/month) which handles deployment, scaling, and custom domain setup.

Step 3: Configure Custom Subdomain (DNS CNAME)

This is the critical step that makes everything first-party:

  1. Choose a subdomain like data.yourdomain.com or collect.yourdomain.com
  2. Create a DNS CNAME record pointing to your Cloud Run URL (e.g., your-project-abc123.a.run.app)
  3. Map the custom domain in Cloud Run: Cloud Run → “Manage Custom Domains” → add your subdomain. SSL is provisioned automatically via Let’s Encrypt.
  4. Verify: Navigate to https://data.yourdomain.com/healthy — it should return “ok”
  5. Update GTM: Set the Server Container URL to https://data.yourdomain.com in Admin → Container Settings

Step 4: Configure the GA4 Client in sGTM

The GA4 Client receives and parses incoming requests:

  1. Open your Server-Side GTM container → “Clients”
  2. The GA4 Client is auto-created. Open its settings.
  3. Enable “Set first-party cookies” — this is the key setting. The client will set the _ga cookie via HTTP Set-Cookie header from your domain, bypassing Safari ITP’s 7-day cap.
  4. Enable the option to read existing JavaScript-set _ga cookies to preserve returning-user recognition during migration.

Step 5: Configure the GA4 Tag in sGTM

  1. Go to “Tags” → “New” → select “Google Analytics: GA4”
  2. Leave the event data source as default (auto-detected from GA4 Client)
  3. Set trigger to “All Events” (where Client Name equals “GA4”)
  4. Optionally: redact IP addresses or remove PII before sending to GA4

Step 6: Update Client-Side GTM to Route Through sGTM

In your Web (client-side) GTM container, find your GA4 Configuration Tag and set the server_container_url:

// Option 1: In GTM Web Container
// GA4 Config Tag → "Send to server container" → https://data.yourdomain.com

// Option 2: Using gtag.js directly
gtag('config', 'G-XXXXXXX', {
  server_container_url: 'https://data.yourdomain.com'
});

// Option 3: First-party script serving (maximum ad-blocker resilience)
// Replace:
<script src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
// With:
<script src="https://data.yourdomain.com/gtag/js?id=G-XXXXXXX"></script>

First-Party Cookie Configuration

This is the core advantage of server-side tagging:

Client-Side Cookies vs. Server-Side Cookies:
  • JavaScript-set cookies: Safari ITP caps to 7 days (or 1 day from ad click). A user who visits every 8 days looks like a new user every time.
  • HTTP-set cookies from your domain: Not capped by ITP. Can persist for full lifetime (up to 400 days per EU regulations). Studies show 20-40% improvement in returning user identification after implementing sGTM.

Verify in Chrome DevTools → Application → Cookies: the _ga cookie should show your domain (e.g., .yourdomain.com) with a proper long-term expiry.

Integrating Facebook Conversions API (CAPI)

Facebook CAPI sends events server-to-server, complementing or replacing the browser pixel:

Setup Steps

  1. Install the template: In sGTM, go to Tags → New → Community Template Gallery → search “Facebook Conversions API”
  2. Get credentials: In Facebook Events Manager → your Pixel → Settings → generate an access token
  3. Configure the tag:
    • Enter your Pixel ID and Access Token
    • Map GA4 events to Facebook events (page_viewPageView, purchasePurchase, etc.)
    • Set the event_id for deduplication with the browser pixel
    • Pass user data: hashed email, phone, fbc/fbp cookies, IP, user agent
  4. Deduplication: Generate a unique event ID client-side, pass it to both the browser pixel and sGTM. Facebook deduplicates automatically using event_id + event_name.
  5. Test: Use Facebook’s Test Events tool with a test_event_code to verify events arrive correctly.

Benefits Summary

Cost Considerations

Estimated Google Cloud Run Monthly Costs:
Monthly PageviewsEstimated Cost
Up to 100,000$0 - $5 (mostly free tier)
100K - 500K$5 - $25
500K - 1M$25 - $50
1M - 5M$50 - $150
5M - 10M$100 - $300

Note: --min-instances 1 adds ~$10-15/month but eliminates cold starts. Managed providers like Stape.io start at ~$20/month.

Testing and Debugging

GTM Server-Side Preview Mode

Click “Preview” in the sGTM UI to see all incoming requests in real time. For each request, inspect:

GA4 DebugView

In GA4 → Admin → DebugView, server-sent events appear when debug_mode: true is set in the client-side config.

Common Issues

GDPR/CCPA Compliance

Server-side tagging does not replace the need for consent. Key considerations:

Migration Strategy

We recommend a phased approach:

  1. Phase 1: Deploy sGTM alongside existing client-side tags. Both run simultaneously. Compare data for a few weeks.
  2. Phase 2: Move GA4 to server-side only. Remove the direct GA4 connection from client-side.
  3. Phase 3: Add Facebook CAPI and other vendor integrations to sGTM.
  4. Phase 4: Gradually remove client-side vendor scripts as server-side equivalents prove reliable.

Conclusion

Server-side tagging with GTM and GA4 is no longer optional — it is the foundation of modern analytics infrastructure. By routing data through your own first-party subdomain, you gain resilience against browser restrictions, improved data accuracy, better page performance, and stronger privacy controls.

The initial setup requires some infrastructure work, but the long-term benefits in data quality and compliance readiness far outweigh the modest hosting costs. Start with GA4, validate your data, then expand to Facebook CAPI and other platforms for a complete server-side analytics stack.