Blog

Pass session metadata between client and server containers

A client-side data layer push is the simplest pattern. For richer signals, custom headers carry more.

When your client GTM fires an event to your tagging server, you can pass arbitrary metadata along with the event. The mechanism depends on what kind of metadata it is and how often it changes.

Per-event metadata: the data layer

For data that changes per event (the product viewed, the form submitted, the link clicked), push it into the data layer alongside the event:

dataLayer.push({
  event: 'view_item',
  ecommerce: { items: [{ item_id: 'SKU-A', price: 29 }] },
  page_section: 'sale',
  internal_test_variant: 'B'
});

In your client GTM, map the data layer fields to event parameters on the GA4 (or other) tag. They forward to the server as part of the event payload.

Per-session metadata: cookies

For data that is consistent across a session (the campaign that brought the user in, the A/B test variant assigned), store in a cookie. Your client GTM reads the cookie and adds it to outgoing events; your server container can also read it directly if it is not HttpOnly.

Once-per-page metadata: a global var

For data that is set once on page load (user role, account tier, page template), set a global JavaScript variable and reference it from a Custom Variable in client GTM:

// In your page header, after authentication:
window.__userContext = {
  role: 'admin',
  tier: 'enterprise',
  account_id: '12345'
};

In client GTM, create a JavaScript Variable that returns window.__userContext.role and add it as a parameter on relevant events.

Custom HTTP headers

For metadata that should not appear in the visible event payload (security tokens, session IDs you do not want logged), use a custom request header. Your client GTM can add headers via the GA4 tag's "Add headers" setting:

'X-Account-Token': '{{ JS - account token }}'

In your server container, read the header with getRequestHeader('x-account-token'). Make sure the header is included in your CORS Allow-Headers; without it, browsers will strip it on cross-origin requests.

When to use which

  • Data layer for per-event business data.
  • Cookies for session-scoped state.
  • Global vars for page-load context.
  • Custom headers for sensitive metadata that should not show in the URL or body.