Skip to content

fix(packages/sui-segment-wrapper): improve session id assignment#1972

Merged
tomasmax merged 2 commits intomasterfrom
improve-session-id-assignment
Mar 16, 2026
Merged

fix(packages/sui-segment-wrapper): improve session id assignment#1972
tomasmax merged 2 commits intomasterfrom
improve-session-id-assignment

Conversation

@kikoruiz
Copy link
Copy Markdown
Member

Summary

Fix GA4 session ID inconsistencies that caused "unassigned" sessions when matching events from Segment (cloud) and client-side "sui" events.

Root cause: gtag.get('session_id') returns incorrect/temporary IDs during the first hits due to a race condition between the API call and the physical cookie write.

Solution: Prioritize reading session ID directly from the GA4 cookie (segment_ga_*) as the source of truth, with API fallback.

Changes

  • Add getGA4SessionIdFromCookie() helper in utils/cookies.js to read session ID from cookie using regex pattern
  • Update getGoogleSessionId() to prioritize cookie value over gtag API
  • Extract checkNewSession() helper to deduplicate session detection logic
  • Add getGA4Data() function to expose complete GA4 context (clientId, sessionId, isNewSession)
  • Export new functions: getGA4Data, getGoogleClientId, getGoogleSessionId
  • Support optional googleAnalyticsCookiePrefix config (defaults to 'segment')
  • Expose GA4 data in window.__GA4_DATA for debugging

Backwards Compatibility

✅ 100% backwards compatible

  • All existing functions maintain same signature and behavior
  • Event flow to Segment unchanged
  • "sui" GA4 init events still trigger correctly
  • Graceful fallbacks if cookie/localStorage unavailable

Benefits

  • Consistent session IDs between client and Segment events
  • Reduced "unassigned" sessions in GA4
  • Better session tracking accuracy
  • Improved debugging capabilities

@tomasmax tomasmax merged commit 8cd6395 into master Mar 16, 2026
3 checks passed
@tomasmax tomasmax deleted the improve-session-id-assignment branch March 16, 2026 09:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants