Resources

Examples & Recipes

Platform-specific integration guides, code examples, and Signals API recipes.

Signals API

Signals Recipes

These recipes show how to use Commerce Index Signals in simple scripts and tools. All examples assume you have already integrated CI Proof (view and purchase events) and have an API key.

Prerequisites: A brand_id assigned by Commerce Index, an API key (X-CI-Api-Key), and active Proof integration.

1. Brand Signals – CLI Summary (Node.js)

File: brand-signals.js

Fetches brand-level activity for the last 30 days and prints a simple summary: total views, total purchases, conversion rate, trends vs the previous 30-day window, and top products by views/purchases.

Use this to quickly get a high-level pulse of how your brand is doing without opening any dashboards.

// brand-signals.js
const fetch = require('node-fetch'); // or global fetch in newer Node

const API_BASE = 'https://commerceindex.com/api';
const API_KEY = process.env.CI_API_KEY;      // set in env
const BRAND_ID = 'brand_xyz';

async function fetchBrandSignals() {
  const url = `${API_BASE}/v1/signals/brand?brand_id=${BRAND_ID}&window=30d`;

  const res = await fetch(url, {
    method: 'GET',
    headers: {
      'X-CI-Api-Key': API_KEY,
      'Content-Type': 'application/json'
    }
  });

  if (!res.ok) {
    console.error(`Error: ${res.status} ${res.statusText}`);
    const errBody = await res.text();
    console.error(errBody);
    process.exit(1);
  }

  const data = await res.json();
  const agg = data.aggregate;
  const trend = data.trend;

  (data.top_products || []).forEach((p, idx) => {
      `${idx + 1}. ${p.title} – views: ${p.views}, purchases: ${p.purchases}, conv: ${(p.conversion_rate * 100).toFixed(2)}%, trend: ${p.trend}`
    );
  });
}

fetchBrandSignals().catch(err => {
  console.error('Unexpected error:', err);
});

Run: CI_API_KEY=your_api_key_here node brand-signals.js

2. Product Signals – Is This Product Hot or Cold? (Python)

File: product_signals.py

Calls the Product Signals endpoint for a single product and prints: views, purchases, conversion rate, trend vs the previous period, an activity tier (high/medium/low) and a short comment.

Use this when you want to evaluate individual SKUs and spot which products are outperforming or underperforming.

# product_signals.py
import os
import requests

API_BASE = "https://commerceindex.com/api"
API_KEY = os.environ.get("CI_API_KEY")
BRAND_ID = "brand_xyz"
PRODUCT_ID = "prod_123"

def fetch_product_signals():
    url = f"{API_BASE}/v1/signals/product"
    params = {
        "brand_id": BRAND_ID,
        "product_id": PRODUCT_ID,
        "window": "7d"
    }
    headers = {
        "X-CI-Api-Key": API_KEY,
        "Content-Type": "application/json"
    }

    resp = requests.get(url, params=params, headers=headers)
    if resp.status_code != 200:
        print("Error:", resp.status_code, resp.text)
        return

    data = resp.json()
    activity = data.get("activity", {})
    trend = data.get("trend", {})
    signal = data.get("signal", {})

    print(f"Brand:   {data.get('brand_id')}")
    print(f"Product: {data.get('product', {}).get('title')} ({data.get('product', {}).get('product_id')})")
    print(f"Window:  {data.get('time_window')}")
    print("")
    print(f"Views:      {activity.get('views')}")
    print(f"Purchases:  {activity.get('purchases')}")
    print(f"Conversion: {round(activity.get('conversion_rate', 0) * 100, 2)}%")
    print("")
    print(f"Views vs prev:      {trend.get('views_vs_prev_period')} ({round(trend.get('views_change_pct', 0), 1)}%)")
    print(f"Purchases vs prev:  {trend.get('purchases_vs_prev_period')} ({round(trend.get('purchases_change_pct', 0), 1)}%)")
    print(f"Conversion vs prev: {trend.get('conversion_vs_prev_period')} ({round(trend.get('conversion_change_pct', 0), 1)}%)")
    print("")
    print(f"Activity tier: {signal.get('activity_tier')}")
    print(f"Comment:       {signal.get('comment')}")

if __name__ == "__main__":
    fetch_product_signals()

Run: CI_API_KEY=your_api_key_here python product_signals.py

3. Context Signals – One-Line Summary for Agents/Tools (Node.js)

File: context-signals.js

Posts a brand + product to the Context API and prints: a one-line headline, key signals (activity, trend, brand background), and optional recommendations.

This is ideal for agents, assistants, or internal tools that need a compact, opinionated summary instead of raw statistics.

// context-signals.js
const fetch = require('node-fetch');

const API_BASE = 'https://commerceindex.com/api';
const API_KEY = process.env.CI_API_KEY;
const BRAND_ID = 'brand_xyz';
const PRODUCT_ID = 'prod_123';

async function fetchContext() {
  const url = `${API_BASE}/v1/signals/context`;

  const body = {
    brand_id: BRAND_ID,
    product_id: PRODUCT_ID,
    country: "US",
    window: "7d"
  };

  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'X-CI-Api-Key': API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });

  if (!res.ok) {
    console.error(`Error: ${res.status} ${res.statusText}`);
    const errBody = await res.text();
    console.error(errBody);
    process.exit(1);
  }

  const data = await res.json();


  (data.key_signals || []).forEach(sig => {
    if (sig.details) {
    }
  });

  if (data.recommendations && data.recommendations.length > 0) {
    data.recommendations.forEach((rec, idx) => {
    });
  }

}

fetchContext().catch(err => {
  console.error('Unexpected error:', err);
});

Run: CI_API_KEY=your_api_key_here node context-signals.js

4. Brand Signals → CSV for BI (Python)

File: brand_signals_to_csv.py

Fetches Brand Signals and writes the top_products block to top_products_signals.csv, with views, purchases, conversion rate, and trend per product.

Use this to pull CI Signals into your BI environment or spreadsheets for further analysis.

# brand_signals_to_csv.py
import os
import csv
import requests

API_BASE = "https://commerceindex.com/api"
API_KEY = os.environ.get("CI_API_KEY")
BRAND_ID = "brand_xyz"

def main():
    url = f"{API_BASE}/v1/signals/brand"
    params = {
        "brand_id": BRAND_ID,
        "window": "30d"
    }
    headers = {
        "X-CI-Api-Key": API_KEY,
        "Content-Type": "application/json"
    }

    resp = requests.get(url, params=params, headers=headers)
    resp.raise_for_status()
    data = resp.json()

    top_products = data.get("top_products", [])

    with open("top_products_signals.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["product_id", "title", "views", "purchases", "conversion_rate", "trend"])
        for p in top_products:
            writer.writerow([
                p.get("product_id"),
                p.get("title"),
                p.get("views"),
                p.get("purchases"),
                round(p.get("conversion_rate", 0) * 100, 2),
                p.get("trend")
            ])

    print("Wrote top_products_signals.csv")

if __name__ == "__main__":
    main()

Each example uses CI_API_KEY read from an environment variable and the production Signals endpoints (/v1/signals/brand, /v1/signals/product, /v1/signals/context). You can adapt these scripts to your own stack (Node, Python, serverless functions, or backend jobs) to embed Commerce Index Signals into your workflows.

Platform Integration

Shopify

Step 1: Add Loader to Theme

Add this to theme.liquid before the closing </body> tag.

{% comment %} Add this to theme.liquid before </body> {% endcomment %}
<script>
  (function(w, d, s, src, name) {
    if (w[name]) { return; }
    var ci = w[name] = function() { ci.q.push(arguments); };
    ci.q = [];
    var el = d.createElement(s);
    el.async = true;
    el.src = src;
    var firstScript = d.getElementsByTagName(s)[0];
    firstScript.parentNode.insertBefore(el, firstScript);
  })(window, document, 'script', 'https://cdn.commerceindex.com/ci.js', 'ci');

  ci('init', { brandId: '{{ shop.permanent_domain | md5 }}' });
</script>
Step 2: Track Product Views

Add this to your product template.

{% comment %} Add this to product.liquid or main-product.liquid {% endcomment %}
<script>
  document.addEventListener('DOMContentLoaded', function() {
    ci('trackView', {
      productId: '{{ product.id }}',
      productSku: '{{ product.selected_or_first_available_variant.sku | escape }}',
      productTitle: '{{ product.title | escape }}',
      productUrl: '{{ shop.url }}{{ product.url }}'
    });
  });
</script>
Step 3: Track Purchases

Add this to the order confirmation page (requires Shopify Plus for checkout.liquid access).

{% comment %} Add this to checkout.liquid or order confirmation page {% endcomment %}
{% if first_time_accessed %}
<script>
  ci('trackPurchase', {
    orderId: '{{ order.id }}',
    currency: '{{ order.currency }}',
    items: [
      {% for line_item in order.line_items %}
      {
        productId: '{{ line_item.product.id }}',
        productSku: '{{ line_item.sku | escape }}',
        productTitle: '{{ line_item.title | escape }}',
        quantity: {{ line_item.quantity }},
        value: {{ line_item.final_price | divided_by: 100.0 }}
      }{% unless forloop.last %},{% endunless %}
      {% endfor %}
    ]
  });
</script>
{% endif %}

Next.js / React

Commerce Index Hook
// hooks/useCommerceIndex.js
import { useEffect } from 'react';

export function useTrackView(product) {
  useEffect(() => {
    if (typeof window !== 'undefined' && window.ci && product?.id) {
      window.ci('trackView', {
        productId: product.id,
        productSku: product.sku,
        productTitle: product.title,
        productUrl: window.location.href
      });
    }
  }, [product?.id]);
}

export function trackPurchase(order) {
  if (typeof window !== 'undefined' && window.ci) {
    window.ci('trackPurchase', {
      orderId: order.id,
      currency: order.currency,
      items: order.lineItems.map(item => ({
        productId: item.productId,
        productSku: item.sku,
        productTitle: item.title,
        quantity: item.quantity,
        value: item.price
      }))
    });
  }
}

Server-Side (Headless)

Node.js Example

For headless setups, you can track purchases server-side after order creation.

// Server-side tracking example (Node.js)
const axios = require('axios');

const CI_API_URL = 'https://commerceindex.com/api';
const CI_API_KEY = process.env.CI_API_KEY;
const CI_BRAND_ID = process.env.CI_BRAND_ID;

// Track purchase after order is created
async function trackPurchase(order) {
  try {
    const response = await axios.post(
      CI_API_URL + '/collect/product-purchase',
      {
        brand_id: CI_BRAND_ID,
        order: {
          order_id: order.id,
          currency: order.currency,
          total_value: order.total,
          items: order.items.map(item => ({
            product_id: item.productId,
            sku: item.sku,
            title: item.title,
            quantity: item.quantity,
            unit_price: item.price
          }))
        },
        context: {
          timestamp: new Date().toISOString()
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'X-CI-Api-Key': CI_API_KEY
        }
      }
    );
    
  } catch (error) {
    console.error('Failed to track purchase:', error.message);
    // Don't block the order process on CI failures
  }
}