Lesson 13 of 15
LocalStorage & SessionStorage
① Connect your GTM container
Paste your container ID to load it into this page. It only ever runs here.
Advanced: use a specific environment
Cookies are not the only place a site keeps client-side state. localStorage persists across visits and sessionStorage lasts only for the current tab. Both are common homes for things like a plan tier or an A/B test variant.
GTM has no built-in variable for either one, so you read them with a Custom JavaScript variable that returns window.localStorage.getItem(...) or its session equivalent. Wrap the read in a try/catch so it never throws when a browser blocks storage.
Goal
Read localStorage and sessionStorage values with Custom JavaScript variables.
Build it in GTM
Create a Custom JavaScript variable for localStorage
Return window.localStorage.getItem('ht_plan'). Wrap it in a try/catch so it never throws when storage is blocked.Create a second Custom JS variable for sessionStorage
Return window.sessionStorage.getItem('ht_ab_variant').Use them in a tag
Send the plan as a user property and the A/B variant as an event parameter, so reporting can segment by them.Verify in Tag Assistant
After clicking the buttons, both variables should resolve to their stored values in the Variables tab.
Debug in Tag Assistant
Copy this lesson's live URL and paste it into GTM Preview, that is the page Tag Assistant connects to. It has the clickable elements, so this page stays clean for reading.
- In your GTM, click Preview.
- Paste the live URL above and click Connect.
- Interact with the live page and watch your tag fire in Tag Assistant.
What you should expect to see
"pro" and "B". In DevTools → Application → Storage you can see both keys, and watch sessionStorage disappear when the tab closes.Verify your container
Built it? Export your container, Admin → Export Container, choose your workspace, then drop the JSON here to check it against this lesson.
Drop your container .json here
or browse · checked in your browser, nothing is uploaded