Google’s readAnalyticsStorage API lets you retrieve GA4’s client ID and session ID inside Google Tag Manager, but only if the user has granted analytics_storage consent. This removes the need for cookie parsing and makes your tracking privacy-compliant.
Here’s exactly how to use it in practice:
1. Enable Consent Mode in GTM
2. Create a Custom Template in GTM
[javascript]
const ids = await readAnalyticsStorage();
if (ids) {
const clientId = ids.clientId;
const sessionId = ids.sessionId;
// Send to your desired platform
}
3. Capture IDs When Consent Is Given
Create a new Tag using your custom template.
Set the trigger to fire when:
Form submissions occur, OR
A specific event is tracked (e.g., purchase, lead).
Make sure your trigger checks for analytics_storage consent.
4. Send IDs to Your Destination
Example: Sending to a CRM
Add a hidden field in your lead form for the GA client ID.
When the form is submitted, GTM passes the ID into that hidden field and sends it along with the form data.
Example: Sending to Google Ads for Enhanced Conversions
5. Test Your Setup
Result: You’ll have reliable, consent-compliant GA4 IDs for attribution and tracking, without breaking privacy laws or relying on fragile JavaScript hacks.