For general data layer concepts, see Data Layers Explained
What the Data Layer Does
The data layer is a JavaScript array (window.dataLayer) that passes structured information from your website to Google Tag Manager. GTM reads this data and uses it to fire tags, populate variables, and send events to analytics platforms.
Initialization
Initialize the data layer before the GTM container script loads:
<script>
window.dataLayer = window.dataLayer || [];
</script>
<!-- GTM container script follows -->
Pushing Page Data
Push page-level information on every page load so GTM tags can access it:
window.dataLayer = window.dataLayer || [];
dataLayer.push({
'pageType': 'article', // homepage, category, product, article, etc.
'pageCategory': 'blog',
'contentTitle': document.title,
'cmsSource': 'keystonejs', // identifies content from KeystoneJS API
'pageLanguage': document.documentElement.lang || 'en'
});
Headless CMS Considerations
Since KeystoneJS is a headless CMS, the data layer lives in your frontend framework — not in KeystoneJS itself. Push content metadata from KeystoneJS's API responses into the data layer when rendering pages:
// After fetching content from KeystoneJS API
dataLayer.push({
'contentType': response.type, // from CMS content model
'contentId': response.id,
'contentAuthor': response.author,
'publishDate': response.published_at,
'contentTags': response.tags?.join(',') || ''
});
User Properties
Push user state for segmentation in analytics:
dataLayer.push({
'userLoggedIn': true,
'userId': 'user_12345', // hashed or internal ID, never PII
'userType': 'subscriber' // anonymous, registered, subscriber, admin
});
Custom Events
Push custom events to trigger GTM tags:
// Form submission
dataLayer.push({
'event': 'form_submit',
'formId': 'contact-form',
'formName': 'Contact Us'
});
// CTA click
dataLayer.push({
'event': 'cta_click',
'ctaText': 'Get Started',
'ctaLocation': 'hero'
});
// File download
dataLayer.push({
'event': 'file_download',
'fileName': 'whitepaper.pdf',
'fileType': 'pdf'
});
Reading Data Layer in GTM
In GTM, create Data Layer Variables to access pushed values:
- Go to Variables → New → Data Layer Variable
- Set the variable name to match the key you pushed (e.g.,
pageType,userLoggedIn) - Use these variables in triggers and tag configurations
Debugging
// View all data layer entries
console.table(window.dataLayer);
// Monitor new pushes in real-time
(function() {
var original = window.dataLayer.push;
window.dataLayer.push = function() {
console.log('dataLayer.push:', arguments[0]);
return original.apply(window.dataLayer, arguments);
};
})();
Also use GTM Preview Mode (click Preview in GTM) to see data layer events in the Tag Assistant panel as you navigate your site.
Next Steps
- GTM Setup — install GTM on KeystoneJS
- GA4 Event Tracking — send events to GA4
- Events Not Firing — troubleshoot data layer issues