Skip to content

getPersistedDataLayerValue β€” GTM Variable Template for GTM

VARIABLES β€Ί GTM
getPersistedDataLayerValue EXTENDED GTM
Direct (.tpl) Apply (.tpl)

Retrieves a value from the GTM dataLayer and persists it across page loads. Returns the latest value when available, or the previously stored value if not. Supports dot notation for nested properties and array indices. β†ͺ️ Returns the current dataLayer value, the last stored value, or undefined if none exists.


GTM Utilities

Access GTM-specific APIs: dataLayer, debug mode, container settings.


Retrieve persisted userId
INPUT
DataLayer Variable Name: userId
DataLayer: {userId: "12345"}
OUTPUT
"12345"
Fallback to stored value
INPUT
DataLayer Variable Name: userId
DataLayer: {} (empty)
Previously stored: "12345"
OUTPUT
"12345"

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

Read-only Preview
getPersistedDataLayerValue
DataLayer Variable Name
πŸ’Ύ The name of the dataLayer variable to retrieve and persist.

Supports dot notation for nested properties:
  βœ“ Top-level variable: "userId", "eventName"
  βœ“ Nested property: "user.email", "ecommerce.purchase.value"
  βœ“ Array index: "products.0.name"

Supported formats:
  βœ“ "String"
Input Setup
Input Function (optional)
βš™οΈ Optional function to apply to the input before processing.

Supported formats:
   βœ“ Function

___________
✏️ Examples

{{toNumber()}} - convert input to number
{{toLowerCase()}} - convert input to lowercase
{{trim()}} - remove whitespace from input
Result Handling
Output Function (optional)
βš™οΈ Optional function to apply to the result before returning it.

Supported formats:
    βœ“ Function

___________
✏️ Examples

{{toCamelCase()}} - convert string to camelCase
{{undefinedTo("x")}} - convert undefined value to "x"
{{filter(GreaterThan(10))}} - keep values greater than 10


πŸ“œ View Implementation Code
/**
* Retrieves a value from the dataLayer and persists it across page loads
*
* @param {string} data.key - The dataLayer variable name to retrieve (supports dot notation)
* @param {Function|string} [data.out] - Optional output handler
*
* Direct-mode specific parameters:
* @param {Function} [data.pre] - Optional pre-processor
*
* @returns {*} The latest value, stored value, or undefined
*
* @framework ggLowCodeGTMKit
*/
const localStorage = require('localStorage');
const templateStorage = require('templateStorage');
const copyFromDataLayer = require('copyFromDataLayer');
const JSON = require('JSON');
const STORAGE_KEY = 'gtm-persistent-data';
const getPersistedDataLayerValue = function(key) {
if (!key) {
return undefined;
}
let cache = templateStorage.getItem(STORAGE_KEY);
if (!cache) {
const storedRaw = localStorage.getItem(STORAGE_KEY);
cache = storedRaw ? JSON.parse(storedRaw) : {};
templateStorage.setItem(STORAGE_KEY, cache);
}
const cachedValue = cache[key];
const freshValue = copyFromDataLayer(key);
if (freshValue !== undefined && freshValue !== cachedValue) {
cache[key] = freshValue;
localStorage.setItem(STORAGE_KEY, JSON.stringify(cache));
return freshValue;
}
return freshValue !== undefined ? freshValue : cachedValue;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const variableName = applyCast(data.pre, data.key);
return out(getPersistedDataLayerValue(variableName));
// ===============================================================================
// Apply mode
// ===============================================================================
/*
return function(key) {
return out(getPersistedDataLayerValue(applyCast(data.pre, key)));
};
*/
___WEB_PERMISSIONS___
[
{
"instance": {
"key": {
"publicId": "access_local_storage",
"versionId": "1"
},
"param": [
{
"key": "keys",
"value": {
"type": 2,
"listItem": [
{
"type": 3,
"mapKey": [
{
"type": 1,
"string": "key"
},
{
"type": 1,
"string": "read"
},
{
"type": 1,
"string": "write"
}
],
"mapValue": [
{
"type": 1,
"string": "gtm-persistent-data"
},
{
"type": 8,
"boolean": true
}
πŸ§ͺ View Test Scenarios (3 tests)
βœ… '[example] Retrieve persisted userId'
βœ… '[example] Fallback to stored value'
βœ… Test empty key returns undefined