How to Fix DatoCMS Tracking Events Not Firing | OpsBlu Docs

How to Fix DatoCMS Tracking Events Not Firing

Fix GA4, GTM, and pixel events not firing on DatoCMS — frontend framework integration, Structured Text data layer timing, and SSG build-time debugging

Common issues and solutions for tracking problems on DatoCMS-powered sites. This guide covers Google Analytics 4, Google Tag Manager, and Meta Pixel troubleshooting.

Common Tracking Issues

1. Events Not Appearing in GA4

Symptoms:

  • No events in GA4 Realtime reports
  • Missing custom events
  • DatoCMS content data not tracked

Diagnosis:

Check if gtag is loaded:

// Browser console
console.log(typeof window.gtag) // should be 'function'
console.table(window.dataLayer)

Solutions:

A. Verify GA4 Installation

Check if tracking script is present:

// View page source
// Look for: gtag/js?id=G-XXXXXXXXXX

Verify environment variable is set:

# .env.local
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX

Check component is rendering:

// app/layout.tsx
import { Analytics } from './components/Analytics'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Analytics /> {/* Should be here */}
        {children}
      </body>
    </html>
  )
}

B. Check for JavaScript Errors

Open browser console (F12):

  • Look for errors preventing script execution
  • Check for CSP (Content Security Policy) blocks
  • Verify no ad blockers are active

C. Verify DatoCMS Data is Pushed

// Check if content data exists
console.log('DatoCMS Post:', post)

// Verify event is called
window.gtag('event', 'datocms_content_view', {
  content_id: post.id,
  content_type: post._modelApiKey,
})

// Check data layer
console.table(window.dataLayer.filter(item =>
  item.event === 'datocms_content_view'
))

D. Enable Debug Mode

gtag('config', 'G-XXXXXXXXXX', {
  'debug_mode': true
})

Then check GA4 DebugView:

  1. Go to GA4 → Admin → DebugView
  2. Verify events appear in real-time

2. GTM Data Layer Issues

Symptoms:

  • GTM tags not firing
  • Data layer variables empty
  • DatoCMS content metadata missing

Diagnosis:

Check GTM Preview mode:

  1. In GTM, click Preview
  2. Enter your URL
  3. Click Connect
  4. Check if container loads

Check data layer in console:

// View data layer
console.table(window.dataLayer)

// Check for DatoCMS events
window.dataLayer.filter(item =>
  item.event?.includes('datocms')
)

// Check specific variable
window.dataLayer.filter(item =>
  item.contentId
)

Solutions:

A. Verify GTM Container ID

# .env.local
NEXT_PUBLIC_GTM_ID=GTM-XXXXXX

Check container loads:

// View page source
// Look for: googletagmanager.com/gtm.js?id=GTM-

B. Check Data Layer Push Timing

Ensure data is pushed before GTM initializes:

// Bad - data pushed after GTM loads
export default function Page({ post }) {
  useEffect(() => {
    // Too late!
    window.dataLayer.push({ contentId: post.id })
  }, [])
}

// Good - data available on page load
export default function Page({ post }) {
  return (
    <>
      <Script
        id="datocms-data"
        strategy="beforeInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
              event: 'datocms_page_view',
              contentId: '${post.id}',
              contentType: '${post._modelApiKey}'
            });
          `,
        }}
      />
      <Article post={post} />
    </>
  )
}

C. Verify GTM Variables

In GTM Preview mode:

  1. Check Variables tab
  2. Verify Data Layer Variables are populated
  3. Check spelling matches exactly
// GTM Variable Name must match data layer key
dataLayer.push({
  contentId: '123', // GTM variable: contentId (case-sensitive)
  contentType: 'blog_post'
})

D. Check GTM Triggers

Verify trigger configuration:

  • Event name matches exactly
  • Trigger fires on correct events
  • No conflicting conditions
// Trigger should listen for:
dataLayer.push({
  event: 'datocms_page_view', // Must match GTM trigger event name
  // ...
})

3. Meta Pixel Not Tracking

Symptoms:

  • No PageView events in Meta Events Manager
  • Custom events missing
  • DatoCMS content not tracked

Diagnosis:

Check if Meta Pixel is loaded:

// Browser console
console.log(typeof window.fbq) // should be 'function'

Use Meta Pixel Helper:

  1. Install Chrome extension
  2. Visit your site
  3. Check for pixel detection

Solutions:

A. Verify Pixel ID

# .env.local
NEXT_PUBLIC_META_PIXEL_ID=1234567890123456

Check pixel loads:

// View page source
// Look for: facebook.net/en_US/fbevents.js
// Look for: fbq('init', '1234567890123456')

B. Check Pixel Installation

// Verify component renders
import { MetaPixel } from './components/MetaPixel'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <MetaPixel /> {/* Should be here */}
        {children}
      </body>
    </html>
  )
}

C. Verify Events Fire

// Test event manually
window.fbq('track', 'PageView')

// Check if DatoCMS event fires
window.fbq('track', 'ViewContent', {
  content_name: post.title,
  content_id: post.id,
})

D. Check Browser Console for Errors

Look for:

  • CSP errors blocking Meta Pixel
  • Ad blocker interference
  • JavaScript errors

4. Preview Mode Contamination

Problem: DatoCMS preview sessions tracked in production analytics.

Solution: Exclude preview mode from tracking:

'use client'

import { useSearchParams } from 'next/navigation'
import { useEffect } from 'react'

export function AnalyticsProvider({ children }) {
  const searchParams = useSearchParams()
  const isPreview = searchParams.get('preview') === 'true'

  useEffect(() => {
    // Only track in production mode
    if (!isPreview && window.gtag) {
      window.gtag('event', 'page_view')
    }
  }, [isPreview])

  // Don't render analytics in preview mode
  if (isPreview) {
    return children
  }

  return (
    <>
      <Analytics />
      {children}
    </>
  )
}

5. Missing DatoCMS Content Metadata

Problem: Events fire but lack DatoCMS-specific data.

Solution: Ensure GraphQL query includes needed fields:

# Bad - missing metadata
query {
  blogPost(filter: { slug: { eq: $slug } }) {
    title
    content
  }
}

# Good - includes tracking metadata
query {
  blogPost(filter: { slug: { eq: $slug } }) {
    id
    title
    slug
    _modelApiKey
    category { title }
    tags { title }
    author { name }
    _publishedAt
    _updatedAt
  }
}

Track with complete data:

export function DatoCMSTracker({ post }) {
  useEffect(() => {
    if (window.gtag) {
      window.gtag('event', 'datocms_content_view', {
        content_id: post.id,
        content_type: post._modelApiKey,
        content_title: post.title,
        category: post.category?.title,
        author: post.author?.name,
        published_at: post._publishedAt,
      })
    }
  }, [post])

  return null
}

6. Events in Development but Not Production

Diagnosis:

Check environment variables:

# Verify production env has tracking IDs
vercel env ls

# Or check deployment logs

Solution:

Ensure environment variables are set in production:

# Vercel
vercel env add NEXT_PUBLIC_GA_MEASUREMENT_ID production

# Or in Vercel dashboard
# Settings → Environment Variables

7. Server-Side Rendering Issues

Problem: window is not defined errors.

Solution: Only access window on client:

// Bad
const gtag = window.gtag

// Good
if (typeof window !== 'undefined') {
  const gtag = window.gtag
}

// Better: Use useEffect
useEffect(() => {
  window.gtag('event', 'page_view')
}, [])

Testing Checklist

GA4 Testing

  • Check browser console for errors
  • Verify gtag function exists: typeof window.gtag
  • Check dataLayer: console.table(window.dataLayer)
  • Enable debug mode
  • View GA4 DebugView
  • Check Network tab for collect requests
  • Verify Measurement ID is correct
  • Check environment variables

GTM Testing

  • Enable GTM Preview mode
  • Verify container loads
  • Check data layer in Preview
  • Verify variables populate
  • Check triggers fire
  • Test tags fire
  • Verify GTM ID is correct

Meta Pixel Testing

  • Install Meta Pixel Helper extension
  • Verify pixel detected
  • Check fbq function exists
  • Test manual event: fbq('track', 'PageView')
  • View Events Manager → Test Events
  • Check Network tab for facebook.com requests
  • Verify Pixel ID is correct

Debugging Tools

Browser Console Commands

// Check tracking status
console.log('GA4:', typeof window.gtag)
console.log('GTM:', typeof window.dataLayer)
console.log('Meta:', typeof window.fbq)

// View data layer
console.table(window.dataLayer)

// Test GA4 event
window.gtag('event', 'test_event', { test: 'value' })

// Test Meta Pixel
window.fbq('track', 'PageView')

// View all DatoCMS events
window.dataLayer.filter(item =>
  item.event?.includes('datocms')
)

Network Tab

  1. Open DevTools → Network
  2. Filter by:
    • google-analytics.com (GA4)
    • googletagmanager.com (GTM)
    • facebook.com or facebook.net (Meta)
  3. Verify requests are sent
  4. Check request payloads

Getting Help

DatoCMS Support:

Analytics Support:

Next Steps

For general tracking troubleshooting, see Global Issues Hub.