Skip to content

Instantly share code, notes, and snippets.

@derekcavaliero
Last active May 13, 2025 19:05
Show Gist options
  • Select an option

  • Save derekcavaliero/ba40441a0fc82e534cef33a29458e7c8 to your computer and use it in GitHub Desktop.

Select an option

Save derekcavaliero/ba40441a0fc82e534cef33a29458e7c8 to your computer and use it in GitHub Desktop.
GA4 Session ID Parsing Function
const parseGa4SessionId = (str) => {
let value;
const parts = str.split('.');
const parser = {
v1: (str) => {
let parsed = {};
const data = str.split('.').slice(2);
let indexMap = {
0: 's',
1: 'o',
2: 'g',
3: 't',
4: 'j',
5: 'l',
6: 'h',
};
data.forEach((value, index) => {
parsed[indexMap[index]] = value;
});
return parsed;
},
v2: (str) => {
let parsed = {};
const data = str.split('.').slice(2).join('');
let keyMap = {};
data.split('$').forEach((segment) => {
let prefix = segment[0];
let key = keyMap[prefix] || prefix;
parsed[key] = segment.substring(1);
});
return parsed;
},
};
if (parts[0].indexOf('GS') === 0) {
value = parser[{
GS1: 'v1',
GS2: 'v2',
}[parts[0]]](str);
} else {
if (str.indexOf('$') > -1) {
str = 'GS2.' + str;
value = parser.v2(str);
} else {
str = 'GS1.' + (parts.length == 2 ? '1.' : '') + str;
value = parser.v1(str);
}
}
return value;
};
@derekcavaliero
Copy link
Author

derekcavaliero commented May 12, 2025

Assumes an ID following any of the following the formats:

GS1.1.1746270489.2.1.1746270616.60.0.0
GS2.1.s1746270489$o2$g1$t1746270616$j60$l0$h0
1746270489.2

1746270489.2 assuming it has been parsed to pull only the [SessionID].[SessionNumber] segments. It would be wise to wrap any call to this method in a try/catch to avoid any errors. This method doesn't cover other possible pre-parsed values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment