Skip to content

Guide · Get customers · · 10 min read

Server-side Conversions API on Cloudflare Workers, step by step

How to send conversions to Meta and LinkedIn from a Worker with event_id deduplication, PII hashing and Consent Mode v2, with no servers to maintain.

Analysis by the Control Research teamJaime, Rafael and Luciano

Ad blockers, third-party cookie restrictions and anti-tracking browsers mean part of your conversions never reach the Meta Pixel or the LinkedIn Insight Tag. The algorithm optimizes on what it sees; if it sees less, it optimizes worse.

The Conversions API (CAPI) fixes this by sending events from your server. The usual setup is a server-side GTM container on a server someone has to maintain. For most B2B sites there is a simpler option: an endpoint on Cloudflare Workers that runs at the edge, needs no servers and costs very little at moderate volume.

This site uses it. Here is the full design.

The principle: one event, one ID, two paths

The key to CAPI is not sending from the server but not counting twice. If the browser sends “Lead” to the Pixel and the server sends “Lead” to the API, Meta must know it is the same event. Both carry the same event_id and the same event name.

Browser                                     Worker
───────                                     ──────
event_id = crypto.randomUUID()
dataLayer.push({ event: 'lead_submit',      POST /api/track (or /api/lead)
                 event_id })                 { name, eventId, consent, ... }
   │                                            │
   ▼                                            ▼
GTM → Pixel (eventID)  ──►  Meta  ◄──  Conversions API (event_id)
                         dedupes on event_name + event_id

In GTM, the Pixel tag must read event_id from the dataLayer and send it as the Event ID. Meta’s official GTM template has a field for it.

Under Colombia’s Law 1581, the GDPR in Spain and a growing number of other regimes, sending data to ad platforms requires consent. The right flow:

  1. Consent Mode v2 initialized before GTM, everything denied by default.
  2. A banner that updates ad_storage, ad_user_data, ad_personalization and analytics_storage separately.
  3. The browser sends the consent state to the Worker along with the event.
  4. The Worker only calls Meta and LinkedIn when ads is granted. It can always store the event in your own database for first-party analytics.

Consent is not just a browser concern. If your CAPI sends everything regardless, the legal problem sits on your server.

The Worker endpoint

A minimal, robust endpoint validates input, stores the event idempotently and sends to platforms in the background so the response is not delayed:

// src/pages/api/track.ts (Astro + Cloudflare adapter)
export const POST: APIRoute = async ({ request, locals }) => {
  const body = await readJson(request, TrackSchema); // Zod: name, eventId UUID, consent…
  locals.cfContext.waitUntil(
    recordEvent(env, request, {
      name: body.name,
      eventId: body.eventId,
      consentAds: body.consent.ads,
      pageUrl: body.pageUrl,
      attribution: body.attribution,
    }),
  );
  return json({ ok: true }, { status: 202 });
};

recordEvent does three things:

// 1. Idempotency: INSERT OR IGNORE on a unique event_id in D1
const r = await env.DB.prepare('INSERT OR IGNORE INTO events (event_id, name, …) VALUES (?1, ?2, …)')
  .bind(input.eventId, input.name /* … */)
  .run();
if (r.meta.changes === 0 || !input.consentAds) return; // duplicate or no consent

// 2. User data: request IP and user agent, _fbp/_fbc cookies, li_fat_id
// 3. Send to Meta and LinkedIn in parallel
await Promise.all([sendMetaCapi(ev, cfg), sendLinkedinCapi(ev, cfg)]);

Database idempotency protects against browser retries and prevents sending the same event twice to platforms.

Hashing and normalizing PII

Meta and LinkedIn accept identifiers such as email and phone only as SHA-256 hashes, and matching depends on normalizing before hashing:

  • Email: trim and lowercase.
  • Phone: digits only, with country code.
  • First and last name: lowercase, trimmed.
async function sha256Hex(input: string) {
  const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));
  return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

crypto.subtle is native in Workers, no libraries needed. One detail: events with PII should leave from an endpoint that already holds the PII, like the one that stores the form. Do not send the email from the browser to a generic tracking endpoint.

Meta: the payload

await fetch(`https://graph.facebook.com/${VERSION}/${PIXEL_ID}/events?access_token=${TOKEN}`, {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({
    data: [{
      event_name: 'Lead',
      event_time: Math.floor(Date.now() / 1000),
      event_id: eventId,           // same one the Pixel received
      action_source: 'website',
      event_source_url: pageUrl,
      user_data,
      custom_data: { score: 86 },
    }],
  }),
});

Validate in Events Manager with a test event code before going live, and check Event Match Quality. If it is low, an identifier is usually missing (email, fbp, fbc) or normalization is wrong.

LinkedIn: conversion rules

LinkedIn works differently: each conversion maps to a conversion rule created in Campaign Manager with a CAPI source. The payload references that rule and requires at least one user identifier (hashed email or the li_fat_id LinkedIn appends to the click URL):

{
  conversion: `urn:lla:llaPartnerConversion:${RULE_ID}`,
  conversionHappenedAt: Date.now(),
  eventId,                                  // dedupes with the Insight Tag
  user: { userIds: [{ idType: 'SHA256_EMAIL', idValue: hashedEmail }] },
}

It goes to https://api.linkedin.com/rest/conversionEvents with LinkedIn’s API version headers. Keep the event-to-rule mapping in an environment variable (LINKEDIN_CONVERSION_RULES) so you do not touch code for every new conversion.

Which events to send

Event Meta LinkedIn Why
Form submitted Lead Lead Primary conversion
Qualified lead (score ≥ 60) Lead + score Qualified lead Optimize for quality, not volume
Meeting booked Schedule Call booked Strong intent signal
Chat started Contact (optional) Micro-conversion for audiences

The next level is sending events from the CRM when a deal advances or is won. That is when ads start optimizing toward revenue instead of forms.

Production checklist

  • Consent Mode v2 with default: denied before GTM loads.
  • event_id generated in the browser and shared by Pixel, Insight Tag and CAPI.
  • The Worker respects marketing consent.
  • PII normalized and hashed; never logged.
  • Idempotency on event_id in the database.
  • Tokens stored as Worker secrets (wrangler secret put), never in the repo.
  • Validated with test codes in Meta and the LinkedIn dashboard.
  • Rate limiting on the endpoint so nobody uses it as a relay.

Want to know where your measurement stands today? The free tracking audit detects which tags are installed and whether Consent Mode is initialized.

We contact you2 minutes

Try Control ARM.

Leave your details and we will write to you. No commitment.

Contact

We reply within one business day.

Rather see it first?

↑↓ navigate · Enter open · Esc close