Tech for Retail 2025 Workshop: From SEO to GEO – Gaining Visibility in the Era of Generative Engines

Back to blog

Google Tag Manager variables: built-in, user-defined and GA4 uses

SEO

Discover Incremys

The 360° Next Gen SEO Platform

Request a demo
Last updated on

1/11/2026

Chapter 01

Example H2
Example H3
Example H4
Example H5
Example H6

This page is for the marketing manager, SEO or analyst who configures GA4 in GTM and wants data they can actually use. Google Tag Manager variables read, transform and reuse the values your tags send and your triggers test.

 

It complements the article on the data layer and is part of our Google Tag Manager guide: here you decide which variable type to choose, how to name it and how to avoid empty values in GA4.

 

Variables, Tags and Triggers: What Each Building Block Provides

 

In GTM, a variable is an information holder: it provides a reusable value to a trigger, a tag or another variable. The operational difference with the other two building blocks is as follows:

 

  • Trigger: decides when to act, on which event and under which condition;
  • Tag: performs the action, for example sending a GA4 event;
  • Variable: provides what to send, and sometimes how to compute it.

 

The same variable can therefore serve as a condition in a trigger and as a parameter in a tag: the built-in variable "Click URL" filters an outbound click, then passes the clicked address to GA4.

 

Built-in vs User-Defined Variables: Choosing the Right Approach for Your Goals

 

Built-in variables: use cases and a methodological limitation

 

Built-in variables are provided by GTM and are not customisable. They cover standard collection and condition needs:

 

  • Pages: full URL, hostname, path, referrer;
  • Clicks: element, classes, ID, target, URL, text;
  • Forms: ID, classes, action URL, text;
  • Scroll and visibility (gtm.* keys): depth, visible ratio, time on screen;
  • Videos (gtm.video* keys): status, duration, progress, title;
  • Errors: message, URL, line, debug mode.

 

Their limitation is methodological: they describe the interface rather than the business context. As soon as a component changes, during a redesign or an A/B test, the conditions that rely on them become fragile.

 

User-defined variables: reading a value or generating one

 

User-defined variables are created when no built-in variable fits. They read an existing value, such as a data layer key, or generate one through transformation or calculation. They are particularly useful to:

 

  • standardise a value, for example a button label;
  • make business data explicit, such as lead_type or cta_location;
  • factorise a setting: an ID, an event name, a mapping rule;
  • reduce duplication across similar tags.

 

Reliability comes when business data already exists as a stable key that GTM simply reads: transformation variables then become finishing tools rather than workarounds.

 

The Key Variable Types to Master for GA4

 

The table below lists the user-defined types that are useful in a GA4-oriented container.

 

TypeWhen to use itExampleRisk
Data LayerRead a key pushed by the siteform_name, page_typeWrong case: empty value
Custom JavaScriptCalculate or transform a missing valueFallback value, URL segmentRequires 'unsafe-eval' in the CSP
ConstantShare a fixed value across tagsEnvironment name, configuration IDHard-coded duplicate left in a tag
Lookup tableMap an exact input to an outputHostname to measurement IDUnplanned case with no default value
Regex tableNormalise variants using patternsfacebook.fr to "Facebook"Pattern too broad, false positives
"Google Tag: Configuration Settings", "Google Tag: Event Settings"Factorise common GA4 parametersParameters shared by several GA4 Event tagsOne change affects every linked tag
URLExtract part of the addressPath, hostname, query parameterURL structure changed by a redesign
1st-party cookieRead a cookie from your domainCookie set by your siteMissing or expired cookie: empty value

 

The "Google Tag: Configuration Settings" and "Google Tag: Event Settings" types have existed since 2023, at the time of writing: they group parameters shared by several GA4 tags instead of re-entering them in each one.

 

Data Layer variable: a stable, case-sensitive key

 

A Data Layer variable reads a key exposed in window.dataLayer. The key name is case-sensitive: if the site pushes form_name and the variable reads formName, it returns an empty value. To read an array element, the variable uses dot notation, for example items.0.item_id.

 

Schema consistency is what makes the difference: same name and same type everywhere (value stays numeric, currency remains a string), camelCase or snake_case without mixing. The data contract and how to push these keys are covered in the parent article.

 

Custom JavaScript variable: calculating with a fallback value

 

A Custom JavaScript variable returns the result of a function. The example below returns 'unknown' if lead_type is missing, which avoids empty parameters in GA4:

 

function() {

 

var leadType = {{DLV - lead_type}};

 

if (!leadType) { return 'unknown'; }

 

return String(leadType).toLowerCase();

 

}

 

This variable should remain the exception: if the site can push the clean value, do so. Otherwise, apply four precautions:

 

  • define a fallback value for every piece of data that may be missing;
  • handle exceptions with try...catch when the read may fail;
  • avoid expensive operations, such as heavy DOM loops;
  • have the function reviewed by both the measurement team and the developers.

 

Constant, lookup table and regex table: centralising and normalising

 

A Constant variable stores a fixed value, such as an environment name, and avoids hard-coding it across several tags.

 

A lookup table applies the rule "if X, then Y": in a multi-site setup, it reads the hostname and returns the domain's measurement ID, rather than maintaining several near-identical tags. It also converts form_name into an event name.

 

A regex table harmonises variants using patterns when data sources are inconsistent, without multiplying scripts.

 

How Variables Feed Your Tags and Triggers

 

A robust tagging plan chains a stable business signal, a clear trigger and tags that draw their parameters from variables.

 

In triggers and GA4 tags: start from a business event

 

In triggers, variables act as conditions. How robust they are depends on what they read:

 

  • custom event: the event key equals a specific value, case-sensitive;
  • URL: a specific path or fragment;
  • click: "Click URL", "Click Text" or "Click Classes", useful but fragile if the interface changes;
  • visibility and scroll: the gtm.* variables.

 

When the trigger has a business impact, such as a lead or a demo request, prefer the business event over an interface detail. On the tag side, the most robust pattern fires a "GA4 Event" tag on that event, for example lead_submit, and populates its parameters with Data Layer variables. A non-standard parameter is then registered as a custom definition in GA4, under exactly the same name.

 

In a custom HTML tag: injecting a variable without weakening the site

 

In a custom HTML tag, the {{VariableName}} syntax injects a GTM variable in place of a hard-coded value. In a multi-domain context, a lookup table on the hostname provides the site identifier: a single tag replaces one copy per site.

 

Preview does not always show the final resolved code: also check the code actually present on the page, and follow four rules:

 

  • limit custom HTML to cases where no native template exists;
  • escape values concatenated into code strings;
  • check that consent has been obtained before any tag that requires permission;
  • document the purpose, required variables and dependencies.

 

Variable Configuration: A Short, Robust Method in GTM

 

Steps 1 to 3: choose the type, lock the format, test

 

Start by deciding whether you need to read or transform a value. The following table matches the most common needs to a variable type and the pitfall to anticipate.

 

NeedVariablePitfall
Switch ID by environment or domainLookup table on the hostnameForgotten domain, no default value
Clean up an inconsistent valueRegex tablePattern too broad, capturing other cases
Read a cookie1st-party cookieCookie missing before consent or expired
Read the dataLayerData Layer variableWrong case or push too late
Calculate a missing valueCustom JavaScript, as a last resortHeavier maintenance, CSP to adapt
Share a fixed valueConstantHard-coded copy forgotten in a tag

 

Before you test, lock down the expected format, a default value and the exact case of the keys. Testing then relies on two tools. In Tag Assistant, GTM's Preview mode, the "Variables" tab shows whether the value appears at the right moment. In GA4, DebugView confirms that the event and its parameters are received.

 

The full procedure is set out in our method to test and debug a GTM container.

 

Step 4: name by family and document

 

The prefix shows a variable's family at a glance:

 

  • DLV - for a Data Layer variable;
  • CJS - for a Custom JavaScript variable;
  • CONST - for a Constant;
  • LT - for a lookup table;
  • RT - for a regex table.

 

Add a business-oriented name, a description (source, format, dependencies) and publish via versions so you can roll back. These prefixes fit into the naming convention of the whole container.

 

B2B Examples: GA4, Key Events and Data Quality

 

In B2B, the aim is to segment performance by intent and editorial context, not only by page. Three setups cover the essentials:

 

  • editorial context: the site pushes the page type, theme and journey stage, which GTM reuses as parameters for CTA clicks;
  • form: a single event per real success, enriched with the lead type from the data layer;
  • CTA labels: "Request a demo" and "Get a demo" reduced to a single value by a lookup table or a regex table.

 

The risk of double sending, hard-coded and via GTM, is dealt with once and for all in our tutorial to set up GA4 with Google Tag Manager. Then check that your GA4 custom definitions carry exactly the names sent: you can then connect themes and formats to qualified leads.

 

Reliability, Compliance and Quality: Common Pitfalls with Variables

 

Why a variable returns "undefined" and how to safeguard it

 

An empty variable in Preview almost always comes from one of the causes below; each has its fix.

 

CauseSymptomFix
Wrong caseKey read under another nameCopy the exact name pushed by the site
Push too lateValue arrives after the trigger firesFire on the event that carries the value
Invalid objectMissing quotes, incorrect syntaxFix the push, check in the console
Expected persistenceValue missing on the next pagePush the key again on every page

 

In addition, add a fallback value and inspect dataLayer in the console to confirm message order.

 

Redesigns and GDPR: what a variable should not read

 

A variable that depends on the DOM (classes, text, structure) breaks at the first interface change. To reduce breakages after a redesign or an A/B test:

 

  • push business information into the data layer, under stable keys;
  • prefer Data Layer variables to DOM selectors;
  • if the DOM is still needed, target stable attributes dedicated to measurement.

 

On compliance, a variable should collect neither directly identifying data nor information unnecessary for the measurement plan. Consent, for its part, is handled once in GTM at trigger level, not variable by variable.

 

Depending on Your Situation

 

The next step depends on what your variables feed today:

 

  • Your custom HTML tags are multiplying. Consolidate and name them using the rules in our article on scripts and tags in GTM.
  • A variable reads a cookie or data subject to consent. Check the CMP, consent state and firing chain described in the guide on cookies and consent in GTM.
  • Your parameters arrive but stay invisible in reports. Create the custom definitions by following our Google Analytics 4 guide.

 

Once your parameters are reliable, the Incremys performance reporting module brings together GA4 and Search Console data to connect each piece of content to its key events and prioritise the ones to improve.

 

FAQ on Google Tag Manager Variables

 

How do you create a user-defined variable without making the container overly complex?

 

Create it only when it serves a recurring purpose, ideally in at least two tags. Give it a name prefixed by its family, document its source and format, and prefer the data layer over DOM extraction. Group transformation logic into tables.

 

When should you use a Data Layer variable rather than a Custom JavaScript variable?

 

Use a Data Layer variable whenever the site can expose the value as a stable key: it is easier to maintain and does not depend on the interface. Reserve Custom JavaScript for calculation, transformation or fallback values, bearing in mind that it requires 'unsafe-eval' under a strict CSP.

 

What is a Constant variable used for in a GTM container?

 

A Constant variable centralises a fixed value, such as an identifier or an environment name, reused across several tags. When an update is needed, you change it in one place instead of correcting each tag, which removes inconsistencies between tags that are meant to share the same setting.

 

What is the difference between a lookup table and a regex table?

 

A lookup table maps an exact input to an output: if the input equals X, the output equals Y. A regex table applies patterns to cover variants in format, domain or case. Choose the first for a finite list of known values, and the second for inconsistent values.

 

How do you use a variable in a GA4 tag to populate event parameters?

 

In the GA4 Event tag, add each parameter, such as lead_type, and set its value to a GTM variable, usually a Data Layer variable. Check the value in Tag Assistant and receipt in DebugView, then register the parameter as a custom definition in GA4.

 

What naming conventions help keep variables maintainable over time?

 

Adopt a prefix per type, such as DLV -, CJS -, CONST -, LT - or RT -, followed by a business-oriented name rather than a UI-driven one. Add a description stating the source and the expected format, and align these prefixes with the container's naming convention.

Discover other items

See all

Next-Gen GEO/SEO starts here

Complete the form so we can contact you.

The new generation of SEO
is on!

Thank you for your request, we will get back to you as soon as possible.

Oops! Something went wrong while submitting the form.