Skip to content

Integrate Shopify Analytics #7

Open
@rylanharper

Description

@rylanharper

Goal

Add basic Shopify Analytics to the project, specifically for tracking page views and cart events.

Research Notes

  1. Shopify uses Monorail as their analytics provider.
    • Reference: hydrogen-react analytics.ts
    • This provides insight into how Shopify's analytics API works.
  2. Found an interesting article on integrating Shopify Analytics in a Next.js environment.

Implementation Idea

Add a new server proxy file, shopify-analytics.ts, to handle the Shopify Analytics API connection. This could allow the frontend to send event data to the backend, which forwards it to Shopify's Monorail endpoint.

Here’s a draft for the proxy handler:

import type { H3Event } from 'h3';

/**
 * Handles requests to the Shopify Analytics API through an API proxy.
 * @param event - The H3 event containing the request data
 * @returns The response from the Shopify Analytics endpoint
 */
export default defineEventHandler(async (event: H3Event) => {
  const { shopify: options } = useRuntimeConfig();
  const { events } = await readBody(event);

  return await $fetch(
    `${options.storefront}/.well-known/shopify/monorail/unstable/produce_batch`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain'
      },
      body: JSON.stringify({
        events,
        metadata: {
          event_sent_at_ms: Date.now()
        }
      })
    }
  );
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions