Tracking Bridge attribution: hybrid Meta (v1)

Pipelines

  1. Theme grabber (sn-utm-grabber/grabber.js) — UTMs, gclid/fbclid, _fbp (synthetic if absent) and _fbc → localStorage, cart attributes, cart metafields (cart_to_order_copyable on order), only while marketing is allowed. Also records the visitor's consent on the cart as _sn_consent (see "Consent"). No event sending — capture only.
  2. App web pixel (sn-pixel-engine) — Subscribes to page_viewed, search_submitted, product_viewed, product_added_to_cart, checkout_started, payment_info_submitted, checkout_completed and sends Meta browser events via the documented facebook.com/tr GET beacon (with eid for dedup). Reads _fbp/_fbc from cookies via the sandbox browser.cookie API and seeds _fbp if missing. Works on both storefront and checkout because Shopify customer events run in both runtimes. ViewContent, AddToCart, InitiateCheckout and AddPaymentInfo are also mirrored to the app (see "Server funnel events" below).
  3. orders/create webhook (with orders/paid as fallback) — Server Meta CAPI Purchase with the same event_id. Reads order metafields (+ optional TrackedOrder), passes the consent gate, upserts ConversionDispatch with metaStatus. Failed sends are retried by the in-process retry drain.

The web pixel posts directly to the app's Railway URL (not an App Proxy): /api/attribution-stage on checkout_completed and /api/e for mirrored funnel events. See "Attribution staging" below for why.

Meta deduplication and Test Events labels

Event Channel Sender
PageView, Search Browser Web pixel → facebook.com/tr
ViewContent, AddToCart, InitiateCheckout, AddPaymentInfo (browser) Browser Web pixel → facebook.com/tr
ViewContent, AddToCart, InitiateCheckout, AddPaymentInfo (server) Server Web pixel → /api/e → batched CAPI (when SERVER_FUNNEL_ENABLED=true)
Purchase (browser) Browser Web pixel → facebook.com/tr on checkout_completed
Purchase (server) Server orders/create → metaCapi.js

PageView is suppressed on order-status / thank-you paths so Purchase remains the canonical signal for that page (matches Meta's official Shopify integration). Tracking Bridge does not emit SubscribedButtonClick — that is auto-detected by fbevents.js and is not part of the standard funnel; the server CAPI Purchase compensates for the loss in attribution coverage.

Advanced matching (Event Match Quality / EMQ)

Both channels send the maximum user_data Meta supports so EMQ — and therefore campaign optimization, ROAS, retargeting, and lookalikes — stay high.

Field Browser /tr (ud[*]) Server CAPI (user_data) Source
em (email, sha256) ✅ on InitiateCheckout / AddPaymentInfo / Purchase ✅ on Purchase Shopify checkout / order
ph (phone, sha256, E.164) ✅ same as above ✅ on Purchase Shopify checkout / order shipping address
fn / ln (first/last name, sha256) ✅ when shipping address is in checkout (PCD) ✅ when GraphQL returns it (PCD) Shopify checkout / order shipping address
ct / st / zp / country (sha256) ✅ when shipping address is in checkout (PCD) ✅ when GraphQL returns it (PCD) Shopify checkout / order shipping address
external_id (sha256) ✅ when customer is logged in ✅ always (orderGid) Shopify customer / order
fbp / fbc ✅ from cookies (synthetic if absent) ✅ from order metafields (grabber) or TrackedOrder Browser cookies / grabber
client_ip_address (auto from browser request) ✅ from payload.client_details.browser_ip Shopify captures the buyer IP during checkout
client_user_agent (auto from browser request) ✅ from payload.client_details.user_agent Shopify captures the buyer UA during checkout

Hashing parity: the SHA-256 produced from event.data.checkout.email in the browser is the same hex string as the SHA-256 produced by the server from the order webhook payload, because both sides apply identical Meta normalization (trim → lowercase, E.164 phone, etc.). This lets Meta dedup with full match quality.

Automatic Advanced Matching cache: Once the buyer enters PII at checkout, the hashed values (em, ph, fn, ln, ct, st, zp, country) are persisted in browser.localStorage (key sn_aam_v1, TTL 30 days). Subsequent events from the same browser — including PageView, ViewContent, AddToCart on a return visit — automatically re-attach those hashes so every browser event reaches Meta with high match quality, mirroring Meta's documented Automatic Advanced Matching behaviour from fbevents.js. Only SHA-256 hex is stored, never plaintext. The pixel's browser.localStorage runs in the storefront's top frame, so both the pixel and the grabber delete the key when marketing consent is withdrawn. Fresh per-event PII always overrides cached values.

PCD requirement: address/name fields are Shopify Protected Customer Data. Until the app is approved (Partner Dashboard → Protected customer data → Request access) Shopify returns these fields as null and we degrade gracefully — only em, ph, fbp, fbc, external_id, client_ip_address are sent. EMQ still rises significantly versus the previous baseline.

Privacy / consent: the web pixel only runs when the buyer allows marketing and hasn't opted out of data sale (handled by Shopify via [extensions.customer_privacy] in shopify.extension.toml: marketing = true, analytics = false, sale_of_data = "enabled"). When consent is denied the pixel is never invoked, so no PII leaves the browser; if it is withdrawn while the pixel is running, the pixel stops sending immediately, and a marketing withdrawal also makes it delete _fbp/_fbc. The server Purchase is a separate path and has its own gate (see "Consent" below).

Why the browser hashes locally instead of sending plaintext: Meta's /tr endpoint accepts both, but client-side SHA-256 keeps raw email/phone out of network logs and ad-blocker mirrors. The server-side CAPI does the same.

Important about webhook IPs: Buyer IP/UA come from payload.client_details.{browser_ip,user_agent} — the values Shopify captured from the actual buyer during checkout. We never use the webhook request's x-forwarded-for / cf-connecting-ip headers because those reflect the Shopify → Railway proxy chain, not the buyer, and forwarding them would actively hurt Meta EMQ.

Server CAPI custom_data parity with the browser: the server Purchase now also sends content_ids, contents (with id/quantity/item_price), content_type, num_items, and order_id. Variant GIDs match the values the browser /tr sends in cd[content_ids], so Meta can cross-reference browser + server purchases at the product level — improving dedup confidence and product-level optimization (ASC, Lookalikes, retargeting).

Why UTMs are not sent to Meta

UTM parameters (utm_source/utm_medium/utm_campaign) and the Google click id (gclid) are captured by grabber.js and persisted as cart attributes + order metafields, but never forwarded to Meta. Meta does not use UTMs for attribution — it uses fbc (which embeds fbclid). UTMs flow to Meta indirectly only through event_source_url so reporting URLs are accurate, and that is sufficient.

UTMs in our pipeline are for:

Google Ads (v2 — not in v1)

gclid is captured on cart/order for a future release. Admin shows Google Ads — Coming soon; no server upload or DB columns in v1.

Attribution staging (direct-to-Railway, NOT App Proxy)

POST {SHOPIFY_APP_URL}/api/attribution-stage (handler: app/routes/api.attribution-stage.jsx). Called by the Web Pixel on checkout_completed with { payload, sig }. payload is a JSON string of { shopDomain, orderId, fbp, fbc, clientUserAgent, pageUrl, revenue, marketingConsent } and sig is HMAC-SHA-256(shop.trackingSecret, payload) hex. The server re-derives the HMAC from the DB-stored secret and verifies, then upserts a TrackedOrder row that the order webhook later reads when assembling the Meta CAPI Purchase payload.

Why not App Proxy under /apps/swiftnode/*: the Shopify strict Web Pixel sandbox rejects any fetch whose target origin equals the storefront's origin — App Proxy paths included — with Requests are not allowed to the same origin. The app's direct Railway URL is cross-origin and therefore the only path that actually delivers the POST. CORS is unlocked with Access-Control-Allow-Origin: *; the body is sent as text/plain to keep the request a CORS "simple request" with no preflight.

Auth scope: Pixel settings are observable in the storefront's pixel JS, so trackingSecret is not a true secret. The HMAC provides tampering friction but not strong authentication. For attribution staging we additionally require a known shop and a well-formed numeric order id; for /api/e see the validation and rate limits in "Server funnel events".

This closes the largest remaining EMQ gap: in direct-to-checkout flows grabber.js never runs on the storefront, so fbp / fbc / client_user_agent never reach the order metafields. The pixel always runs in checkout, so this path fills the gap. Server CAPI still prefers order-metafield values when present (they reflect the customer's first-touch attribution).

Express-checkout race recovery: Buy it now / Shop Pay / Apple Pay / Google Pay create checkouts that bypass the cart, so the order webhook sometimes wins the race against the pixel POST. When processOrderWebhook.server.js finds no TrackedOrder row on the first read, it polls for it (1s / 2s / 3s / 3s / 3s) before dispatching the Meta CAPI Purchase. This keeps EMQ high on express-checkout orders without requiring a queue.

Consent

Consent states in Shopify

Shopify tracks four purposes: analytics, marketing, preferences and sale of data. The cookie banner offers Accept, Decline (necessary cookies only) and Manage preferences (a choice per purpose). In US states with opt-out laws visitors can also opt out of data sale on the "Your privacy choices" page, and a browser GPC signal counts as that opt-out. Until the visitor answers, regions that require consent block every non-essential purpose and other regions allow all of them.

Visitor Web pixel Grabber Server Purchase
Accepted all, or marketing only Runs Captures, marketing=yes send (TrackedOrder)
Declined, or only analytics/preferences Doesn't run Clears its data, marketing=no skip (marker)
Opted out of data sale / GPC Doesn't run Captures, sale_of_data=no send with LDU (marker)
No answer, consent-required region Doesn't run Writes nothing defer once, then skip (region)
No answer, other region Runs Captures send (TrackedOrder)
Withdrew marketing on the storefront Stops sending, deletes _fbp/_fbc Clears its data, marketing=no skip (marker)
Withdrew marketing in checkout Stops sending, deletes _fbp/_fbc, stages the order with marketingConsent=false Not running; clears its data on the next storefront page skip (TrackedOrder)

The _sn_consent cart attribute

The grabber loads Shopify's Customer Privacy API itself (Shopify.loadFeatures, 3s timeout) and writes nothing when it can't. It records the visitor's answer on the cart as _sn_consent, e.g. marketing=yes;sale_of_data=no. The leading underscore hides it in checkout; it reaches the order as a note attribute (admin order → Additional details) and carries no personal data. It is written:

When marketing is declined or withdrawn, the grabber deletes _fbp/_fbc, sn_bridge_attribution_v1 and the pixel's sn_aam_v1, blanks the attribution cart attributes, deletes the swiftnode.* cart metafields (when a Storefront token is configured) and writes marketing=no. It also does this on page load when attribution is still stored without consent, which covers a decline in another tab or in checkout. The grabber doesn't run in checkout, so there the pixel deletes _fbp/_fbc and sn_aam_v1 as soon as marketing is withdrawn.

The server parses the marker in app/lib/conversion/consentMarker.server.js. It is deliberately not one of the keys synced to order metafields.

Decision for the server Purchase

The pixel is consent-gated by Shopify, but the server Purchase comes from the order webhook, which fires for every order. app/lib/conversion/consentGate.server.js decides per order, before deliverMeta, in both the webhook and the retry drain, using the most direct evidence first:

  1. TrackedOrder (the pixel staged the order at purchase time): marketingConsent === false → skip, otherwise → send. It wins over an older marker, e.g. for a visitor who declined on the storefront and accepted in checkout.
  2. _sn_consent on the order: marketing=no → skip; marketing=yes;sale_of_data=no → send with LDU; marketing=yes → send.
  3. Region: the buyer's region is resolved from the order shipping/billing address, falling back to the shop's country, and matched against the shop's Shopify consentPolicy (Admin GraphQL, needs read_privacy_settings; cached 6h). If the policy can't be read, EEA + UK + CH count as consent-required and the US as sale-of-data opt-out.
    • Consent required (EU/UK-style) → defer once by 10 minutes without spending a retry attempt (metaError = "Awaiting consent evidence"), in case the pixel row is late. Still nothing on the next pass → skip.
    • Sale-of-data opt-out region (US states with opt-out laws) → send with Meta Limited Data Use (data_processing_options: ["LDU"], country/state 0 so Meta geolocates).
    • Otherwise → send.

Grabber attribution on the order (fbp, fbclid, utm_*, …) is not consent evidence: it can predate a decline.

Every decision is logged, e.g. [consent] mode=log decision=skip source=marker shop=… orderGid=… reason="…"; region decisions add country= and location=. The "Meta CAPI Purchase sent" line ends with consent=<decision>/<source>.

CONSENT_ENFORCEMENT=log (default) only logs and always sends without LDU. CONSENT_ENFORCEMENT=enforce applies the decision.

Limitations

Server funnel events (/api/e)

POST {app origin}/api/e (handler: app/routes/api.e.jsx). The pixel derives the URL from the origin of its trackingEndpoint setting, so no extra pixel setting or per-shop settings re-sync is needed. The path is deliberately neutral, since blocklists match words like "track", "pixel" and "collect".

For ViewContent, AddToCart, InitiateCheckout and AddPaymentInfo the pixel sends the /tr beacon and then posts the same event (same eid, same hashed user_data, custom_data, user agent and current consent) as a signed { payload, sig } body, the same format as attribution staging. Consent is tracked live through customerPrivacy.subscribe("visitorConsentCollected"); when marketing or sale of data is denied, neither /tr nor the mirror is sent.

The server:

Meta deduplicates each mirrored event against its browser twin by event_name + event_id, so the server copy only counts when /tr was blocked.

Rollout: deploy the server with the switch off, then shopify app deploy the pixel, then set SERVER_FUNNEL_ENABLED=true. Turning the switch off stops forwarding immediately without a pixel deploy.

Smoke test / PoC (Meta Test Events)

  1. Save Pixel ID + CAPI token + optional test event code in Meta settings.
  2. Enable UTM Grabber theme app embed (UTM/click-id capture only); shopify app deploy.
  3. Sync pixel on Home (writes Pixel ID into web pixel settings); disable official Meta channel app.
  4. Open Test Events with the same test_event_code.
  5. Storefront home → PageView (Browser).
  6. Product page → ViewContent (Browser) (+ ViewContent (Server) with the same event_id when SERVER_FUNNEL_ENABLED=true; same for the next three steps).
  7. Search a query → Search (Browser) (optional).
  8. Add to cart → AddToCart (Browser).
  9. Start checkout → InitiateCheckout (Browser).
  10. Submit payment → AddPaymentInfo (Browser).
  11. Complete order → Purchase (Browser) + Purchase (Server) with the same event_id. Test Events shows both rows; reporting merges them.
  12. Confirm ConversionDispatch.metaStatus = sent on Setup & Test.
  13. Block facebook.com in DevTools (Network → Block request domain) and repeat 6–10: only the Server rows should appear.

Consent checks (a store with the cookie banner on; each run in a new private window, entering from a link with ?fbclid=test123, ordering with a shipping address in a consent-required country):

  1. Decline → no facebook.com/tr requests. The order's Additional details show _sn_consent with marketing=no and no fbp/fbc. Log: decision=skip source=marker.
  2. Accept → browser and server events as above. Log: decision=send source=tracked.
  3. Manage preferences, marketing only → the pixel runs. Log: decision=send source=tracked.
  4. Manage preferences, analytics only → no pixel. Log: decision=skip source=marker.
  5. Accept, then withdraw marketing in Manage preferences on the storefront before checkout → _fbp/_fbc are deleted. Log: decision=skip source=marker.
  6. Accept, start checkout, then withdraw marketing in checkout → no more facebook.com/tr or /api/e requests, and _fbp/_fbc disappear from the store's cookies at once. Log: decision=skip source=tracked. Repeat once entering without ?fbclid.
  7. With CONSENT_ENFORCEMENT=enforce, repeat 1 and 4 → no server Purchase in Test Events.
  8. Optional: US opt-out state (VPN to California), data-sale opt-out page enabled, a GPC browser such as Brave → decision=send_ldu source=marker. Without a VPN, with enforce: enter without ?fbclid, don't answer the banner, block the app's domain in DevTools so the pixel can't stage the order, and order with a California address → decision=send_ldu source=region. "Meta CAPI Purchase sent" confirms Meta accepted the LDU fields.

Troubleshooting: