Cosmic (formerly Cosmic JS) is a headless CMS that delivers content via REST and GraphQL APIs. Like other headless CMS platforms, Cosmic itself never renders HTML — your frontend framework does. Analytics issues always trace back to how your frontend (Next.js, Gatsby, Nuxt, Astro, etc.) integrates the content and handles script injection.
Cosmic-Specific Debugging Approach
Since Cosmic is API-only, debugging analytics means checking two layers: (1) is Cosmic delivering the expected data, and (2) is your frontend rendering the tracking code correctly.
Verify Cosmic API Responses
# Check if your Cosmic bucket delivers analytics config
curl -s "https://api.cosmicjs.com/v3/buckets/YOUR_BUCKET/objects?query=%7B%22type%22:%22site-settings%22%7D&read_key=YOUR_KEY&props=slug,title,metadata" \
| python3 -m json.tool | grep -i "tracking\|analytics\|gtm"
// In browser console, check what Cosmic data made it to the page
console.log('Cosmic data:', window.__COSMIC_DATA || window.__NEXT_DATA__?.props);
// Check for analytics scripts
document.querySelectorAll('script[src*="gtag"], script[src*="gtm"]').forEach(s => {
console.log('Analytics script:', s.src);
});
Check Framework Integration Layer
// For Next.js sites using Cosmic
console.log('Next.js data:', JSON.stringify(window.__NEXT_DATA__?.props?.pageProps?.cosmicData || 'none').substring(0, 200));
// For Gatsby sites using Cosmic
console.log('Gatsby data:', window.__GATSBY_DATA ? 'present' : 'missing');
// For Astro sites using Cosmic
console.log('Astro:', document.querySelector('[data-astro-source]') ? 'detected' : 'not found');
Most Common Cosmic Analytics Issues
1. API Data Missing During Static Build
Symptoms: Analytics works in local dev but not on the deployed site. The tracking ID or custom script field is empty in the build output.
Root cause: During static generation, your build process fetches from Cosmic's API. If the API times out, the read key is wrong, or the object is in draft status, the analytics config field returns empty.
Diagnosis:
# Test the API directly with your build environment's read key
curl -s "https://api.cosmicjs.com/v3/buckets/YOUR_BUCKET/objects/YOUR_SLUG?read_key=YOUR_KEY" \
| python3 -m json.tool | grep -c "metadata"
# Should return 1 if the object exists
Fix: Add fallback analytics config in your frontend code:
// Next.js + Cosmic example
const trackingId = cosmicSettings?.metadata?.ga_tracking_id
|| process.env.NEXT_PUBLIC_FALLBACK_GA_ID;
2. Preview/Draft Mode Firing Production Analytics
Symptoms: Pageview counts spike during content editing. Draft content URLs appear in GA reports.
Root cause: Cosmic's preview mode loads your frontend with draft content. If analytics is not suppressed in preview mode, all editorial previews get tracked.
Fix:
// Detect Cosmic preview mode
const isCosmicPreview = new URLSearchParams(window.location.search).has('preview') ||
new URLSearchParams(window.location.search).get('status') === 'draft';
if (isCosmicPreview) {
window['ga-disable-G-XXXXXXX'] = true;
}
3. Webhook Rebuilds Creating Tracking Gaps
Symptoms: Content editors save changes in Cosmic, but the live site serves stale content (including old analytics config) for several minutes.
Root cause: Cosmic sends webhooks on content save. Your hosting platform triggers a rebuild, but the build + deploy pipeline takes time.
Fix: Use ISR or on-demand revalidation instead of full rebuilds:
// Next.js webhook handler for Cosmic
export default async function handler(req, res) {
const { type, data } = req.body;
if (type === 'object.edited.published' && data?.slug === 'site-settings') {
await res.revalidate('/');
return res.json({ revalidated: true });
}
return res.json({ revalidated: false });
}
4. GraphQL Query Not Fetching Analytics Fields
Symptoms: Page content loads fine but analytics metadata fields are missing.
Root cause: Your GraphQL query does not include the analytics-related metadata fields. Cosmic's GraphQL API only returns fields you explicitly request.
Fix: Ensure your query includes the full metadata:
query GetSiteSettings {
getObject(bucket_slug: "your-bucket", slug: "site-settings", read_key: "YOUR_KEY") {
title
metadata {
ga_tracking_id
gtm_container_id
custom_head_scripts
}
}
}
5. Client-Side Navigation Skipping Pageviews
Symptoms: Only the initial page load fires analytics. Subsequent navigation shows no hits.
Root cause: Your frontend framework uses client-side routing, and navigation between Cosmic-powered pages does not trigger full page reloads.
Fix: Hook into your framework's router events:
// Next.js App Router
'use client';
import { usePathname } from 'next/navigation';
import { useEffect } from 'react';
export function CosmicAnalytics() {
const pathname = usePathname();
useEffect(() => {
gtag('event', 'page_view', {
page_path: pathname,
page_title: document.title
});
}, [pathname]);
return null;
}
Environment Considerations
- Cosmic is SaaS: No server to manage, no caching layer to clear on the CMS side. All caching is on your frontend hosting
- Bucket regions: Cosmic buckets can be in different regions. Ensure your build server has fast access to the Cosmic API region your bucket is in
- Media optimization: Cosmic provides an image CDN (imgix). Large images served through it can affect page load timing and LCP
- Object type schema: Analytics config should be in a singleton object type (e.g., "Site Settings") rather than in individual page objects, to ensure consistency
Performance Issues
- LCP Issues - API fetch latency and framework hydration timing
- CLS Issues - Layout shifts from async content loading and image CDN delivery
Tracking Issues
- Events Not Firing - Debug API failures, preview mode leakage, and client-side routing gaps
Related Resources
- Cosmic documentation
- Global Issues Hub for platform-agnostic solutions