Last active
May 13, 2025 19:05
-
-
Save derekcavaliero/ba40441a0fc82e534cef33a29458e7c8 to your computer and use it in GitHub Desktop.
GA4 Session ID Parsing Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assumes an ID following any of the following the formats:
1746270489.2assuming it has been parsed to pull only the[SessionID].[SessionNumber]segments. It would be wise to wrap any call to this method in atry/catchto avoid any errors. This method doesn't cover other possible pre-parsed values.