Server-side Facebook and Instagram ad tracking without GTM, with consent built in
If you run Facebook or Instagram ads, you've probably been told to "add the Conversions API". The browser Pixel misses conversions: ad blockers, Safari's tracking limits and tabs closed too early all drop events before t
If you run Facebook or Instagram ads, you've probably been told to "add the Conversions API". The browser Pixel misses conversions: ad blockers, Safari's tracking limits and tabs closed too early all drop events before they reach Meta. Meta's answer is to send the same events from your server too.
The usual path is a server-side Google Tag Manager container, often on a paid host. That works, but it's a lot of machinery if all you want is to send a few conversion events from your site and backend.
This post covers what any Conversions API setup has to get right, with code, and then shows a small open-source relay I wrote that does it in one service.
The five things you have to get right
1. Deduplication: one conversion, one count
If the Pixel and your server both report a purchase, Meta needs to know it's the same purchase. The rule is simple: send the same event_id from both sides, along with the same event_name.
const eventId = crypto.randomUUID();
// Browser
fbq('track', 'Purchase', { value: 49.90, currency: 'EUR' }, { eventID: eventId });
// Server (same id)
{ event_name: 'Purchase', event_id: eventId, ... }
Forget this and your conversions are counted twice, which quietly wrecks your cost-per-result numbers.
2. Hashing, with Meta's normalization rules
Contact data (em, ph, fn, ln, ct, zp, db, external_idβ¦) must be normalized, then SHA-256 hashed. The normalization is where most homemade implementations go wrong:
- emails: trim and lowercase, so
[email protected]becomes[email protected]; - phones: digits only, with the country code, so
06 12 34 56 78(France) becomes33612345678; - names: lowercase, no punctuation, no spaces;
- dates of birth:
YYYYMMDD.
Some fields must not be hashed: client_ip_address, client_user_agent, fbp and fbc.
3. fbp and fbc for match quality
The Pixel stores two first-party cookies: _fbp (the browser) and _fbc (the ad click). Sending them with server events improves how well Meta matches your events to people. If _fbc isn't set yet but the URL has an fbclid parameter, you can build it: fb.1.<timestamp>.<fbclid>.
4. Consent
This is the one many vendors skip. Moving tracking to the server does not remove the need for consent in the EU and UK. If the visitor refused marketing cookies, the event shouldn't go to Meta at all, from the browser or from your server.
5. Reliability
The Conversions API rejects events older than 7 days, rejects a whole batch if one event is invalid, and sometimes returns transient errors. You need a queue, retries with backoff, and a way to isolate the one bad event so it doesn't block the others.
A relay that does all of that
CAPI Relay is a small open-source (MIT) Node.js service, with one dependency and a Postgres database, that sits between your site and the Conversions API.
browser (Pixel + capi.js) βββΆ CAPI Relay βββΆ Meta Conversions API
your backend ββPOST /v1/eventsβββΆ β
consent Β· hashing Β· dedup Β· queue Β· retries
On your website
Load the helper after your Pixel:
<script>
window.capi = window.capi || function () { (capi.q = capi.q || []).push(arguments) };
</script>
<script async src="https://t.myshop.com/capi.js"></script>
From your cookie banner, once the visitor accepts marketing cookies:
capi('consent', true); // and capi('consent', false) if they withdraw it
Then use capi('track', β¦) instead of fbq('track', β¦). It fires the Pixel and the relay with the same event ID:
capi('track', 'Purchase',
{ value: 49.90, currency: 'EUR' },
{ userData: { em: '[email protected]', ph: '06 12 34 56 78' }, eventId: 'order-1042' });
Until consent is granted, the helper sends nothing, not even to the relay. It never sets cookies; it only reads _fbp/_fbc and builds fbc from fbclid when needed.
From your backend
For order confirmations, CRM updates or offline sales:
curl -X POST https://t.myshop.com/v1/events \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"events":[{"event_name":"Purchase","event_id":"order-1042","consent":true,
"event_source_url":"https://www.myshop.com/checkout",
"user_data":{"em":"[email protected]","client_ip_address":"203.0.113.7","client_user_agent":"Mozilla/5.0 β¦"},
"custom_data":{"value":49.9,"currency":"EUR"}}]}'
Each event must say "consent": true; events without it are dropped and never stored.
What happens inside
- Hashing on arrival, before anything touches the database, following Meta's normalization rules. Values already hashed are passed through.
-
Deduplication: the same
event_name+event_idis accepted once. - A durable Postgres queue with exponential backoff. An invalid batch is split until the bad event is isolated, so the others still go through.
- Expiry: events that would be older than 7 days are marked expired instead of being retried forever.
- Short retention: stored events are deleted after 7 days by default.
- Browser endpoint locked down: CORS limited to your own sites, plus rate limiting.
A dashboard that tells you what's wrong
/admin (password-protected) shows the delivery rate, the queue, events dropped for lack of consent, duplicates, and Meta's own error messages. If your token is wrong, you see "Invalid OAuth access token" right there, and events wait in the queue until you fix it. A button sends a test event to Events Manager's Test events tab.
Deploying it
It's a plain Dockerfile, so it runs anywhere you can run a container with Postgres. There's also a one-click Railway template that sets up the relay, Postgres over the private network, and generated secrets.
You need three values:
-
META_PIXEL_ID: your dataset (Pixel) ID from Events Manager. -
META_ACCESS_TOKEN: Events Manager β your dataset β Settings β Conversions API β Generate access token. No Meta app review is needed. -
ALLOWED_ORIGINS: your site, for examplehttps://www.myshop.com.
Then put the relay on a subdomain of your site (t.myshop.com), so the browser sends the Pixel's first-party cookies to it.
Before going live
- Make sure your Pixel itself only loads after consent, and that your banner calls
capi('consent', β¦). - Mention the Conversions API in your privacy policy.
- Don't send sensitive data (health, for example). Meta's Business Tools Terms forbid it.
Links
- Documentation: jean82290.github.io/capi-relay
- Source (MIT): github.com/jean82290/capi-relay
- Meta's docs: Conversions API, deduplication, customer information parameters
Disclosure: I'm the author of CAPI Relay. If you deploy it through the Railway template, I receive a share of Railway's hosting fees; running it from the Dockerfile costs me nothing. Not affiliated with Meta. "Facebook" and "Instagram" are trademarks of Meta Platforms, Inc.
Questions or feedback are welcome in the comments or on GitHub.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.