Facebook Pixel

Add the Pixel Script

Partytown Script

Set the script element's type attribute to text/partytown. For example:

<script type="text/partytown">
  // insert pixel script here
</script>

Proxy Requests

The connect.facebook.net response does not provide the correct CORS header, and a reverse proxy should be used. Below is an example of setting the resolveUrl config to proxy the connect.facebook.net requests. Please see Proxying Requests for more information.

Proxying with Server Handlers

If you're using a server framework like Nuxt 3, you can handle proxying dynamically using API routes. Below is an example configuration that dynamically fetches resources based on the provided URL and returns the response with appropriate headers:

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const url = String(query?.url) || null;
 
  if (!url || !url.includes("connect.facebook.net")) {
    throw createError({
      status: 500,
      message: "Invalid URL",
    });
  }
 
  // Fetch the file content dynamically based on the URL
  const response = await $fetch(url).catch((error) => {
    throw createError({
      status: 500,
      message: `Failed to fetch resource: ${error.message}`,
    });
  });
 
  setResponseHeaders(event, {
    "Access-Control-Allow-Origin": "*", // Ensures proper CORS handling
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Allow-Methods": "POST, GET, OPTIONS, PUT, DELETE",
    "Content-Type": "application/x-javascript; charset=utf-8",
    "Cache-Control":
      "public, max-age=5, s-maxage=5, stale-if-error=2678400, stale-while-revalidate=86400", // Add necessary caching headers
  });
 
  return response;
});

Forward Events

Facebook Pixel uses the fbq() function to send events. In order for Partytown to forward the calls to window.fbq({..}), the forward config should add "fbq". Please see forwarding events and triggers for more information.

Example Config

// https://partytown.qwik.dev/configuration
{
  resolveUrl: function(url) {
    if (url.hostname === "connect.facebook.net") {
      var proxyUrl = new URL('https://my-reverse-proxy.com/');
      proxyUrl.searchParams.append('url', url.href);
      return proxyUrl;
    }
    return url;
  },
  forward: [
    "fbq"
  ]
}

Please see the integration docs for framework specific configuration.