Tracking Bridge attribution: hybrid Meta (v1)
Pipelines
- Theme grabber (
sn-utm-grabber/grabber.js) — UTMs,gclid/fbclid,_fbp(synthetic if absent) and_fbc→localStorage, cart attributes, cart metafields (cart_to_order_copyableon 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. - App web pixel (
sn-pixel-engine) — Subscribes topage_viewed,search_submitted,product_viewed,product_added_to_cart,checkout_started,payment_info_submitted,checkout_completedand sends Meta browser events via the documentedfacebook.com/trGET beacon (witheidfor dedup). Reads_fbp/_fbcfrom cookies via the sandboxbrowser.cookieAPI and seeds_fbpif 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). orders/createwebhook (withorders/paidas fallback) — Server Meta CAPI Purchase with the sameevent_id. Reads order metafields (+ optionalTrackedOrder), passes the consent gate, upsertsConversionDispatchwithmetaStatus. 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.
- Why
/trfrom the web pixel and notfbq: Shopify's strict sandbox cannot loadfbevents.js(no realdocument.head), so we use Meta's officially supported noscript GET endpoint. It acceptseidfor dedup, advanced matching params viaud[…], and standardcd[value]/cd[currency]/cd[content_*]. Realfbqwould only add automatic browser fingerprinting we don't need for v1. - Shared
event_idfor Purchase:sn_order_{numericOrderId}(metaEventIdForOrderindispatchSend.server.js). - Meta dedupes Pixel (browser) + CAPI (server) with the same
event_name+event_idwithin 48h. Test Events shows both rows on purpose — reporting (Events Manager → Overview) merges them. _fbpmatching: Withoutfbevents.js, Meta never sets_fbp. The web pixel and grabber both seed a syntheticfb.1.{ts}.{rand}if the cookie is missing, so server CAPI (which reads cart-attribute → order metafield) can pair with the browser/trevent.- Pixel ID: Saved in Meta settings → DB → web pixel
settings(webPixelUpdate). The web pixel reads it directly; theme metafields are not required for event sending. - CAPI token: DB only; not synced to web pixel settings.
- Merchant must disable the Shopify Facebook & Instagram channel app; otherwise an extra official
fbqmay appear.
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:
- Shopify Admin — "Sources" report and
order.customAttributesfor merchant visibility - Google Analytics (GA4) — automatic via the page URL
- Email marketing / Klaviyo — they can read UTMs off the order
- Google Ads (v2, not in v1) —
gclidwill go to Enhanced Conversions when implemented
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:
- together with every attribution write;
- on every banner answer (
visitorConsentCollected), even when there is no cart yet; - once per cart for visitors who answered earlier or opted out of data sale. The grabber remembers the cart it marked in
sessionStorageand watches thecartcookie, so carts created by a cart drawer are marked too.
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:
- 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. _sn_consenton the order:marketing=no→ skip;marketing=yes;sale_of_data=no→ send with LDU;marketing=yes→ send.- 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, needsread_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/state0so Meta geolocates). - Otherwise → send.
- Consent required (EU/UK-style) → defer once by 10 minutes without spending a retry attempt (
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
- Buy it now and other express checkouts skip the cart, so the order has no marker. The decision falls back to the TrackedOrder or the region.
- Third-party consent banners only work if they pass the visitor's choice to Shopify with
customerPrivacy.setTrackingConsent. Otherwise Shopify keeps the region default: in consent-required regions everything stays blocked, including our pixel, and the server defers and then skips. - IP location vs order address: Shopify picks the banner and defaults by the visitor's IP location, while the region step uses the order address. The marker removes the mismatch for every visitor who answered the banner.
- Withdrawal in checkout followed by a page load: the pixel that started with checkout handles a withdrawal there: it stages the order with
marketingConsent=false, so the server skips. If the checkout page loads again after the withdrawal (a reload, or a return from an off-site payment such as PayPal), Shopify doesn't start the pixel, the cart still saysmarketing=yes, and the server sends.
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:
- Returns 204 and drops everything unless
SERVER_FUNNEL_ENABLED=true(global switch, no per-shop flag). - Rate limits per IP (600/min) and per shop (6000/min), caps the body at 16KB, requires a known installed shop and a valid HMAC.
- Validates and bounds every field (
app/lib/funnel/funnelEvent.server.js): event name allowlist, event time within ±10 minutes, httpsevent_source_url, user agent required, hashed fields must be SHA-256 hex, values/quantities capped. The secret is readable in the storefront, so a valid signature is not proof of origin. - Drops replays of the same
event_idper shop for 30 minutes. - Adds
client_ip_addressfrom the browser request (x-forwarded-for), then buffers in memory per shop and flushes to Meta in batches of up to 1000 every 5s (or at 200 queued), with one retry. Nothing is written to the database per event. Pending events are flushed on SIGTERM; a crash loses at most a few seconds of funnel events, which is acceptable because the browser copy still exists. - Logs
[funnel] last minute received= sent= failed= dropped=once a minute when there was traffic.
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)
- Save Pixel ID + CAPI token + optional test event code in Meta settings.
- Enable UTM Grabber theme app embed (UTM/click-id capture only);
shopify app deploy. - Sync pixel on Home (writes Pixel ID into web pixel settings); disable official Meta channel app.
- Open Test Events with the same
test_event_code. - Storefront home → PageView (Browser).
- Product page → ViewContent (Browser) (+ ViewContent (Server) with the same
event_idwhenSERVER_FUNNEL_ENABLED=true; same for the next three steps). - Search a query → Search (Browser) (optional).
- Add to cart → AddToCart (Browser).
- Start checkout → InitiateCheckout (Browser).
- Submit payment → AddPaymentInfo (Browser).
- Complete order → Purchase (Browser) + Purchase (Server) with the same
event_id. Test Events shows both rows; reporting merges them. - Confirm
ConversionDispatch.metaStatus = senton Setup & Test. - Block
facebook.comin 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):
- Decline → no
facebook.com/trrequests. The order's Additional details show_sn_consentwithmarketing=noand nofbp/fbc. Log:decision=skip source=marker. - Accept → browser and server events as above. Log:
decision=send source=tracked. - Manage preferences, marketing only → the pixel runs. Log:
decision=send source=tracked. - Manage preferences, analytics only → no pixel. Log:
decision=skip source=marker. - Accept, then withdraw marketing in Manage preferences on the storefront before checkout →
_fbp/_fbcare deleted. Log:decision=skip source=marker. - Accept, start checkout, then withdraw marketing in checkout → no more
facebook.com/tror/api/erequests, and_fbp/_fbcdisappear from the store's cookies at once. Log:decision=skip source=tracked. Repeat once entering without?fbclid. - With
CONSENT_ENFORCEMENT=enforce, repeat 1 and 4 → no server Purchase in Test Events. - 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, withenforce: 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:
- DevTools (storefront tab) → Network → filter
facebook.com/tr. Should see one row per event. If empty: web pixel is disconnected (Home → Sync pixel) ormetaPixelIdis missing in pixel settings. - Setup & Test "No probe response" usually means admin can't iframe the storefront (X-Frame-Options) — it does not mean the embed is off. Verify directly in a storefront tab.
- Server Purchase but no browser Purchase: ad blocker is dropping
facebook.com/trrequests. Server CAPI still wins; nothing to fix. - No server funnel rows: check
SERVER_FUNNEL_ENABLED=trueon the server, DevTools → Network → filter/api/e(expect 204), and the[funnel]log line. A 401 means the pixel'strackingSecretsetting is out of sync (open the app or save settings to re-sync); 400 usually means a non-https page URL or a clock skew over 10 minutes. - Two Purchase rows in Test Events with matching
event_idis expected (one Browser, one Server). Reporting deduplicates. - Server Purchase for a visitor who declined: find the order's
[consent]line.mode=lognever blocks.source=trackedmeans the pixel staged the order, so consent was given at purchase time. Withsource=region, check the order's Additional details: no_sn_consentmeans the grabber didn't mark the cart (embed off, Buy it now, or the Customer Privacy API didn't load). Withsource=markerandmarketing=yesafter a withdrawal in checkout, the checkout page loaded again after the withdrawal (see Limitations).