UCP Session Manager

This JavaScript module manages the UCP session on the client-side, including session creation, data storage, and retrieval.

JavaScript
class UCPSessionManager {
  constructor() {
    this.sessionId = this.getOrCreateSessionId();
    this.sessionData = this.loadSession();
    this.webhookUrl = 'https://your-xano.xano.io/api/webhook';
  }

  getOrCreateSessionId() {
    let sessionId = sessionStorage.getItem('ucp_session_id');
    if (!sessionId) {
      sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      sessionStorage.setItem('ucp_session_id', sessionId);
    }
    return sessionId;
  }

  trackEvent(eventType, eventData = {}) {
    const event = {
      timestamp: new Date().toISOString(),
      type: eventType,
      data: eventData,
      page: window.location.pathname
    };
    this.sessionData.userHistory.push(event);
    this.saveSession();
    this.sendWebhook('event_tracked', event);
  }

  updateConsent(purpose, granted) {
    this.sessionData.consentStatus[purpose] = {
      granted: granted,
      timestamp: new Date().toISOString()
    };
    this.saveSession();
    this.sendWebhook('consent_updated', { purpose, granted });
  }
}

Consent Management UI

Build a consent management interface in Webflow using vanilla JavaScript.

HTML + JavaScript

Xano Webhook Endpoint

Set up a webhook endpoint in Xano to receive data from Webflow.

Xano Function Stack
// Xano Function Stack Pseudo-code
const payload = $input.body;
const eventType = payload.eventType;
const session = payload.session;

// Validate
if (!session.sessionId || !eventType) {
  return { success: false, error: 'Missing fields' };
}

// Transform Data
const customerData = {
  email: session.email,
  tags: ['ucp-user', `session-${session.sessionId}`]
};

// Shopify Sync
const customer = await shopify_find_or_create_customer(customerData);
await shopify_update_metaobject(customer.id, 'ucp_user_profile', {
  consent_status: JSON.stringify(session.consentStatus),
  user_history: JSON.stringify(session.userHistory)
});

// Google AI Stream
await google_ai_stream_event({
  user_id: customer.id,
  event_type: eventType,
  timestamp: new Date().toISOString()
});

return { success: true, customerId: customer.id };

Idempotency Implementation

Implement idempotency checks when syncing data to Shopify.

JavaScript
async function syncToShopify(session, eventType, eventData) {
  const idempotencyKey = `${session.sessionId}_${eventType}_${Date.now()}`;
  
  // Check if already processed
  const existing = await xano.query('idempotency_log')
    .where('idempotency_key', idempotencyKey)
    .first();
  
  if (existing) {
    return existing.result;
  }
  
  try {
    const customer = await shopify.findOrCreateCustomer(session.email);
    await shopify.updateMetaobject({
      ownerId: customer.id,
      namespace: 'ucp',
      key: 'user_profile',
      value: JSON.stringify(session)
    });
    
    const result = { success: true, customerId: customer.id };
    await xano.insert('idempotency_log', {
      idempotency_key: idempotencyKey,
      result: result
    });
    
    return result;
  } catch (error) {
    console.error('Sync error:', error);
    throw error;
  }
}

Create Customer with Metaobject

GraphQL mutation to create a customer with metafields.

GraphQL
mutation createCustomer($input: CustomerInput!) {
  customerCreate(input: $input) {
    customer {
      id
      email
      metafields(first: 10) {
        edges {
          node {
            namespace
            key
            value
          }
        }
      }
    }
  }
}

// Variables
{
  "input": {
    "email": "user@example.com",
    "tags": ["ucp-user"],
    "metafields": [
      {
        "namespace": "ucp",
        "key": "consent_status",
        "value": "{\"analytics\":true}",
        "type": "json"
      }
    ]
  }
}

Metaobject Definition Setup

Steps to create a Metaobject definition in Shopify admin.

  1. 01. Navigate to Settings โ†’ Custom data โ†’ Metaobjects
  2. 02. Create new Metaobject definition: "UCP User Profile"
  3. 03.

    Add these fields:

    • โ€ข consent_status (JSON)
    • โ€ข user_history (JSON)
    • โ€ข last_seen (DateTime)
  4. 04. Associate with customer records

JWT Token Generation

Generate JWT tokens for secure communication between services.

JavaScript
function generateJWT(userId, sessionId) {
  const payload = {
    userId: userId,
    sessionId: sessionId,
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + (60 * 60)
  };
  
  const secret = process.env.JWT_SECRET;
  return jwt.sign(payload, secret);
}

Security Best Practices

  • โ–ช Always use TLS/HTTPS for all API communications
  • โ–ช Store API keys and secrets in environment variables
  • โ–ช Implement rate limiting on webhook endpoints
  • โ–ช Use JWT tokens with short expiration times
  • โ–ช Validate and sanitize all incoming data
  • โ–ช Log all security-related events for auditing