How to Add Google Analytics 4 to Cosmic | OpsBlu Docs

How to Add Google Analytics 4 to Cosmic

Install and configure GA4 on Cosmic — manual gtag.js installation, Enhanced Measurement setup, and verification steps.

For general GA4 concepts, see Google Analytics Platform Overview

Prerequisites

  • A Google Analytics 4 property created at analytics.google.com
  • Your GA4 Measurement ID (format: G-XXXXXXXXXX, found in Admin → Data Streams → your stream)
  • Admin access to your Cosmic site

Installation

Cosmic-Specific Setup

Cosmic is a headless CMS — install GA4 in your frontend framework. When building with Next.js, Gatsby, Nuxt, or a static site generator, add the gtag.js snippet to your app's entry HTML or use the framework's analytics plugin. Cosmic delivers content via API only — it has no HTML rendering layer.

gtag.js Code

Add this to your site's <head> section:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXXXX');
</script>

Replace G-XXXXXXXXXX with your actual Measurement ID.

Alternative: Install via GTM

If you've already installed GTM on Cosmic, add GA4 as a GTM tag instead of using gtag.js directly:

  1. In GTM → Tags → New → Google Analytics: GA4 Configuration
  2. Enter your Measurement ID
  3. Set trigger to All Pages
  4. Preview → Test → Publish

GTM vs gtag.js: GTM adds a management layer — you can update GA4 configuration, add events, and manage consent without touching site code. For simple setups (just GA4), direct gtag.js is fine. If you also need Meta Pixel, GTM, or other tags, use GTM.

Enhanced Measurement

GA4's Enhanced Measurement automatically tracks common events without code changes:

Event What It Tracks Enabled by Default
Page views Every page load and client-side navigation Yes
Scrolls When user scrolls past 90% of page height Yes
Outbound clicks Clicks to external domains Yes
Site search Search queries (reads URL parameters like ?q= or ?search=) Yes
Video engagement YouTube embedded video play, progress, complete Yes
File downloads Clicks on links to files (PDF, XLSX, DOCX, etc.) Yes
Form interactions Form start and submit (if enabled) No

Enable/disable in GA4 Admin → Data Streams → your stream → Enhanced Measurement (gear icon).

SPA / Client-Side Routing

Since Cosmic-powered sites typically use client-side routing, the default GA4 page_view event only fires on the initial page load. Subsequent navigations happen without a full page reload.

Fix — Use GTM History Change trigger: In GTM, create a trigger with type "History Change" and use it for your GA4 page_view tag (alongside or instead of the "All Pages" trigger).

Fix — Manual gtag event: If using gtag.js directly, fire page_view on route changes:

// React Router example
import { useLocation } from 'react-router-dom';
import { useEffect } from 'react';

function useGA4PageTracking() {
  const location = useLocation();
  useEffect(() => {
    if (typeof gtag === 'function') {
      gtag('event', 'page_view', {
        page_path: location.pathname + location.search,
        page_title: document.title,
      });
    }
  }, [location]);
}

Verification

After installation, verify GA4 is collecting data:

  1. Realtime Report — In GA4, go to Reports → Realtime. Visit your site in another tab — you should see yourself as an active user within 30 seconds.
  2. Google Tag Assistant — Go to tagassistant.google.com, enter your site URL, and click Connect. The assistant shows which Google tags fire and whether they're configured correctly.
  3. Browser Console — Open DevTools (F12) and run:
    console.log('dataLayer:', window.dataLayer);
    console.log('gtag:', typeof gtag === 'function' ? 'Loaded' : 'NOT loaded');
    
  4. Network TabFilter for google-analytics.com/g/collect to see GA4 event hits leaving the browser.

Common Verification Issues

  • No data in Realtime — Check for ad blockers (test in incognito with extensions disabled), verify Measurement ID is correct, ensure the page you're viewing actually has the tracking code.
  • Tag fires but no data — Check that your GA4 property and data stream match. A common mistake is using a UA ID (UA-XXXXXXX) instead of GA4 (G-XXXXXXXXXX).
  • Duplicate events — If you see double page views, you may have both gtag.js and GTM firing GA4 tags. Use one method, not both.

Next Steps