Build a structured data layer for your Directus-powered site to power Google Tag Manager tags and variables.
Base Data Layer Structure
Page Load Data Layer
// utils/dataLayer.ts
export function initializeDataLayer(item?: any) {
if (typeof window === 'undefined') return;
window.dataLayer = window.dataLayer || [];
const baseData = {
event: 'page_load',
page: {
path: window.location.pathname,
title: document.title,
url: window.location.href,
},
};
if (item) {
baseData.content = {
type: item.__collection,
id: item.id,
title: item.title || item.name,
status: item.status,
dateCreated: item.date_created,
dateUpdated: item.date_updated,
};
}
window.dataLayer.push(baseData);
}
Directus Collection Data
export function pushDirectusCollection(collection: string, items: any[]) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'collection_view',
collection: {
name: collection,
itemCount: items.length,
items: items.map(item => ({
id: item.id,
title: item.title || item.name,
status: item.status,
})),
},
});
}
Event Tracking
Form Submissions
export function trackDirectusFormSubmit(collection: string, itemId: string) {
window.dataLayer?.push({
event: 'form_submit',
form: {
collection: collection,
item_id: itemId,
success: true,
},
});
}
Search Events
export function trackDirectusSearch(query: string, results: any[]) {
window.dataLayer?.push({
event: 'search',
search: {
term: query,
results_count: results.length,
collections: [...new Set(results.map(r => r.__collection))],
},
});
}
Creating GTM Variables
Collection Type
- Variable Type: Data Layer Variable
- Data Layer Variable Name:
content.type - Name:
DLV - Collection Type
Content ID
- Data Layer Variable Name:
content.id - Name:
DLV - Content ID
- Data Layer Variable Name:
Content Status
- Data Layer Variable Name:
content.status - Name:
DLV - Content Status
- Data Layer Variable Name:
Next Steps
- Install GTM - Set up GTM container
- GA4 Events - Use data layer for GA4
- Troubleshoot Events - Debug tracking issues
For general data layer concepts, see Data Layer Guide.