Setting Up Data Layer for Tag Manager
Data Layer is a JavaScript array through which your site sends structured data to Google Tag Manager. GTM reads the Data Layer and uses this data in tags and triggers. Proper Data Layer architecture allows marketers to configure tags independently without code changes.
Initialization
Data Layer must be initialized before loading GTM:
<script>
window.dataLayer = window.dataLayer || [];
// Global page data
window.dataLayer.push({
pageType: '{{ $pageType }}', // 'product', 'category', 'checkout', 'confirmation'
siteLanguage: '{{ app()->getLocale() }}',
{% if auth()->check() %}
userId: {{ auth()->id() }},
userType: '{{ auth()->user()->isB2B() ? "b2b" : "b2c" }}',
userPlan: '{{ auth()->user()->plan }}',
{% endif %}
});
</script>
<!-- GTM snippet follows -->
Event Structure
Standard: each event contains event (name), thematic data, and optionally ecommerce:
// Good structure
dataLayer.push({
event: 'product_add_to_cart',
ecommerce: {
currency: 'RUB',
value: product.price,
items: [{
item_id: product.id,
item_name: product.name,
item_brand: product.brand,
item_category: product.category,
price: product.price,
quantity: qty
}]
}
});
Clearing Previous ecommerce Data
Before each e-commerce event, clear previous data — otherwise GTM may mix them:
// Must do before each e-commerce event
dataLayer.push({ ecommerce: null });
dataLayer.push({
event: 'view_item',
ecommerce: { /* new data */ }
});
Setting Up Variables in GTM
In GTM, create variables of type "Data Layer Variable":
-
dlv - ecommerce.value→ecommerce.value -
dlv - ecommerce.items→ecommerce.items -
dlv - userId→userId
These variables are used in GA4 tags to pass parameters.
Triggers for Events
In GTM, create a "Custom Event" trigger with the event name from Data Layer:
- Trigger type: Custom Event
- Event name:
product_add_to_cart - Fire on: All Custom Events
Debugging
// View all Data Layer events in console
window.dataLayer.forEach((item, index) => {
if (item.event) console.log(index, item.event, item);
});
GTM Preview Mode shows Data Layer in the right panel for each event — this is the main debugging tool.
Server-Side Data Layer (SSR)
With SSR (Next.js, Nuxt), data can be embedded in HTML on the server, eliminating undefined flashing:
// On server
const initialDataLayer = [
{
event: 'page_data',
pageType: 'product',
product: { id: product.id, name: product.name, price: product.price }
}
];
<script>
window.dataLayer = <?= json_encode($initialDataLayer) ?>;
</script>
Setup time: 2–3 days for complete Data Layer architecture with documentation for marketers.







