Building Your Own Conversion Tracking Technology

Understanding Conversion Tracking

You likely already understand the basics of conversion tracking. To ensure we're on the same page, here's a brief overview:

Conversion tracking allows you to monitor and analyze user interactions on your website. It is a powerful tool used by platforms such as Facebook and Google to assess the effectiveness of advertising campaigns. By tracking conversions, you can gain insights into user engagement with your ads and optimize your strategies for better results.

How Conversion Tracking Works in 3 Steps

  1. User Clicks and Accesses Your Website

    • When a user clicks a link to your website, a cookie is stored in their browser. This cookie ID can be passed through the URL as a parameter or generated when the user first lands on the page, linking interactions with a specific ad or access point.
  2. Script Fires on Chosen Actions

    • A script on the website activates when the user performs certain actions, such as adding a product to the cart or making a purchase. This script sends data about these interactions to the server.
  3. Data Storage and Analysis

    • The server stores the information in a database, where it can be analyzed to evaluate ad performance and understand user behavior on your website.

Building Your Own Conversion Tracking Technology

Step 1 - Create the Client-Side Script

We need to develop a script that can be embedded in the website's HTML code to store cookies and fire events. We'll code this in vanilla JavaScript to ensure smooth browser performance.

1. Set a Cookie

Create a function to set a cookie that tracks user actions.

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        expires = "; expires=" + date.toUTCString();
    }

    // Extract the top-level domain
    var hostParts = window.location.hostname.split(".");
    var topDomain = hostParts.slice(-2).join("."); // e.g., example.com
    var cookieDomain = "; domain=." + topDomain;

    document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=None; Secure" + cookieDomain;
}

2. Query URL Parameters

Create a function to extract parameters from the URL, such as the session ID.

function getURLParameter(name) {
    var param = new RegExp("[?&]" + name + "=([^&#]*)").exec(window.location.href);
    return param === null ? null : decodeURIComponent(param[1].replace(/\+/g, " "));
}

3. Set a Session Cookie

Combine the functions to set a cookie if the URL contains the session ID. Set the cookie to last for 30 days.

var session_id = getURLParameter("session_id");
if (session_id != null) {
    setCookie("session_id", session_id, 30);
}

4. Track User Events

Create a function to send events to the server when a user performs certain actions on the website.

window.trackEvent = async function(eventName, eventData) {
    try {
        var cookie = getCookie("session_id");
        sendEvent({
            name: eventName,
            details: eventData,
            session: cookie,
        });
    } catch (error) {
        console.error("Failed to process event:", error);
    }
};

5. Send Event Data to the Server

Create a function to perform a POST request to your tracking server.

function sendEvent(event) {
    if (event.session && event.session !== "") {
        var payload = {
            event: event.name,
            details: event.details,
            session: event.session,
        };

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "https://api.example.com/pixel", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log("Event data successfully sent!");
                } else {
                    console.error("Failed to send event data: " + xhr.statusText);
                }
            }
        };
        xhr.send(JSON.stringify(payload)); // Correctly send the payload as a JSON string
    } 
}

By following these steps, you can build a robust conversion tracking system to monitor user interactions on your website and optimize your advertising strategies effectively.

5. Make the functions accessable on the entire site

We need to make sure that we can access the functions on all pages of the website, in order for us to fire events in different situations

  window.vbtracker = {
    setCookie: setCookie,
    setAttributionInfo: setAttributionInfo,
    sendEvent: sendEvent,
    getURLParameter: getURLParameter,
    trackEvent: trackEvent,
  };

How to Deploy the Script on Clients' Browsers

Now that we have the client-side script ready, the next step is to deploy it on websites. There are three primary methods to do this:

1. Paste Code Directly Inside the <head> Tag

Pros:

  • Simple Implementation: Easy to implement by directly adding the script into the HTML <head> tag of the website.

Cons:

  • Manual Updates Required: Any updates to the script require manual changes on all websites' source codes.
  • Visibility: The script is exposed in the website's source code, making it easy for others to find and research.

Example:

<head>
  <script>
    // Your tracking script here
  </script>
</head>

2. Host the Script on a Server and Import it via an Endpoint

Pros:

  • Centralized Updates: Changes to the script are automatically applied to all websites without manual updates.
  • Flexibility: Easier to manage and update the script centrally.

Cons:

  • Initial Setup: Requires setting up a backend server with an endpoint to serve the script.
  • Loading Time: The website needs to download the script on every page load, though the impact is usually minimal.
  • Server Load: As your application grows, you'll need to manage server load efficiently to ensure consistent performance.

Example:

<head>
  <script src="https://yourserver.com/path/to/your/script.js"></script>
</head>

Setting Up the Server:

  1. Create a Server: Use Node.js, Python, or any backend technology to create a server.
  2. Serve the Script: Configure an endpoint to serve the JavaScript file.

Node.js Example:

const express = require('express');
const app = express();
const port = 3000;

app.get('/script.js', (req, res) => {
  res.sendFile('/path/to/your/script.js', { root: __dirname });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Server-Side Handling of Conversion Events

To complete your conversion tracking technology, you need to set up a server to handle incoming events, store them, and perform analysis. Here’s how you can achieve this:

Step 2 - Set Up the Server to Handle Events

  1. Create an Endpoint to Receive Events

    You need an endpoint that listens for incoming POST requests from your client-side script. This endpoint will receive the event data and store it in your database.

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    const port = 3000;
    
    // Middleware to parse JSON bodies
    app.use(bodyParser.json());
    
    // Endpoint to receive event data
    app.post('/pixel', (req, res) => {
      const event = req.body;
      // Validate and process the event data
      if (event.session && event.event) {
        // Store event in database (to be implemented)
        storeEvent(event);
        res.status(200).send('Event data received');
      } else {
        res.status(400).send('Invalid event data');
      }
    });
    
    // Function to store event data (implementation below)
    function storeEvent(event) {
      // Database logic here
    }
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    

Final Thoughts

By following these steps, you can build a robust conversion tracking technology that allows you to monitor user interactions on your website and optimize your advertising strategies effectively. This system not only helps in capturing crucial data but also provides insights to drive better marketing decisions.

Remember to comply with privacy laws and regulations, such as GDPR and CCPA, by ensuring users' consent before tracking and securely storing their data.