Measuring Conversion Rates

In modern web applications, understanding and optimizing conversion rates is essential for growth and success. Telemetry provides a powerful way to track, measure, and visualize conversion rates over time. In this article, we'll explore how to set up conversion rate tracking in a Node.js application using the Telemetry API, and how to visualize this data with a graph.

Setting Up Telemetry

Before we can start tracking conversions, we need to set up Telemetry. For this example, we'll use the Telemetry JavaScript SDK.

First, install the Telemetry SDK in your project:

npm install telemetry-sh

Then, initialize the Telemetry client in your application with your API key:

import telemetry from "telemetry-sh";

telemetry.init("YOUR_API_KEY");

Tracking Conversion Events

To measure conversion rates, we need to track relevant events such as page views and successful conversions. We'll set up routes in an Express application to simulate these events.

Setting Up Express

First, let's set up a basic Express application. If you don't already have Express installed, you can add it to your project with the following command:

npm install express

Now, create a simple Express server:

const express = require('express');
const telemetry = require('telemetry-sh');

telemetry.init("YOUR_API_KEY");

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

app.use(express.json());

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

Logging Page Views and Conversions

Next, we'll create routes to log page views and conversions. We'll use Telemetry to log these events with relevant metadata.

app.post('/page-view', (req, res) => {
  const { userId, page } = req.body;
  
  telemetry.log('page_view', {
    userId,
    page,
    timestamp: new Date().toISOString()
  });

  res.status(200).send('Page view logged');
});

app.post('/conversion', (req, res) => {
  const { userId, conversionType } = req.body;
  
  telemetry.log('conversion', {
    userId,
    conversionType,
    timestamp: new Date().toISOString()
  });

  res.status(200).send('Conversion logged');
});

Analyzing and Visualizing Conversion Rates

To analyze and visualize conversion rates, we'll query the logged events and calculate conversion rates over specified time intervals. We'll use Chart.js to render the graph.

Querying Data

First, let's create an endpoint to query the logged data from Telemetry:

app.get('/api/conversion-rates', async (req, res) => {
  const startDate = req.query.startDate;
  const endDate = req.query.endDate;

  const pageViews = await telemetry.query(`
    SELECT
      date_trunc('day', timestamp) as day,
      COUNT(*) as count
    FROM
      page_view
    WHERE
      timestamp BETWEEN '${startDate}' AND '${endDate}'
    GROUP BY
      day
  `);

  const conversions = await telemetry.query(`
    SELECT
      date_trunc('day', timestamp) as day,
      COUNT(*) as count
    FROM
      conversion
    WHERE
      timestamp BETWEEN '${startDate}' AND '${endDate}'
    GROUP BY
      day
  `);

  res.json({ pageViews, conversions });
});

Visualizing Data with Chart.js

Finally, we'll create a simple HTML dashboard to display the conversion rates as a graph:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Conversion Rate Dashboard</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <h1>Conversion Rate Dashboard</h1>
  <form id="date-form">
    <label for="start-date">Start Date:</label>
    <input type="date" id="start-date" name="start-date" required>
    <label for="end-date">End Date:</label>
    <input type="date" id="end-date" name="end-date" required>
    <button type="submit">Get Conversion Rates</button>
  </form>
  <canvas id="conversionChart"></canvas>

  <script>
    document.getElementById('date-form').addEventListener('submit', async (event) => {
      event.preventDefault();
      
      const startDate = document.getElementById('start-date').value;
      const endDate = document.getElementById('end-date').value;

      const response = await fetch(`/api/conversion-rates?startDate=${startDate}&endDate=${endDate}`);
      const data = await response.json();

      const pageViews = data.pageViews.reduce((acc, pv) => {
        acc[new Date(pv.day).toISOString().split('T')[0]] = pv.count;
        return acc;
      }, {});

      const conversions = data.conversions.reduce((acc, cv) => {
        acc[new Date(cv.day).toISOString().split('T')[0]] = cv.count;
        return acc;
      }, {});

      const dates = Object.keys(pageViews).sort();
      const conversionRates = dates.map(date => {
        const pvCount = pageViews[date] || 0;
        const cvCount = conversions[date] || 0;
        return pvCount > 0 ? (cvCount / pvCount) * 100 : 0;
      });

      const ctx = document.getElementById('conversionChart').getContext('2d');
      new Chart(ctx, {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
            label: 'Conversion Rate (%)',
            data: conversionRates,
            borderColor: 'rgba(75, 192, 192, 1)',
            borderWidth: 1,
            fill: false
          }]
        },
        options: {
          scales: {
            x: {
              type: 'time',
              time: {
                unit: 'day'
              }
            },
            y: {
              beginAtZero: true,
              ticks: {
                callback: function(value) {
                  return value + '%';
                }
              }
            }
          }
        }
      });
    });
  </script>
</body>
</html>

Conclusion

By following these steps, you can easily track, measure, and visualize conversion rates over time using Telemetry. This setup allows you to monitor user interactions and conversion events, providing valuable insights to optimize your application's performance and user experience.

Last updated