Skip to main content

Cruxstack Guides

Welcome to the Cruxstack guides! Here you'll find practical examples, best practices, and step-by-step tutorials to help you get the most out of Cruxstack across all platforms.

Quick Start Guides

Getting Started with Node.js

Learn how to integrate Cruxstack into your Node.js application in minutes.

Getting Started with Browser SDK

Track user interactions in your web application with our browser SDK.

Framework-Specific Integration

React Applications

import React, { useEffect } from "react";
import { init, cruxCustom, getUserTraits } from "@cruxstack/browser-sdk";

function App() {
useEffect(() => {
// Initialize the SDK
init({
clientId: "web_demo_client_001", // Required
customerId: "cust-2201", // Optional
customerName: "Acme, Inc.", // Optional
// userId: 'user-8731', // Optional; omit for anonymous
autoCapture: true, // Optional (default: true)
debugLog: false, // Optional (default: false)
});
}, []);

const handleButtonClick = () => {
cruxCustom("purchase_completed", {
productId: "SKU-123",
amount: 99.99,
currency: "USD",
});
};

return <button onClick={handleButtonClick}>Sign Up</button>;
}

Vue.js Applications

<template>
<button @click="trackEvent">Sign Up</button>
</template>

<script>
import { init, cruxCustom } from "@cruxstack/browser-sdk";

export default {
name: "SignupButton",
mounted() {
// Initialize the SDK
init({
clientId: "web_demo_client_001", // Required
customerId: "cust-2201", // Optional
customerName: "Acme, Inc.", // Optional
// userId: 'user-8731', // Optional; omit for anonymous
autoCapture: true, // Optional (default: true)
debugLog: false, // Optional (default: false)
});
},
methods: {
async trackEvent() {
cruxCustom("purchase_completed", {
productId: "SKU-123",
amount: 99.99,
currency: "USD",
});
},
},
};
</script>

Angular Applications

import { Component, OnInit } from "@angular/core";
import { init, cruxCustom } from "@cruxstack/browser-sdk";

@Component({
selector: "app-signup-button",
template: '<button (click)="trackEvent()">Sign Up</button>',
})
export class SignupButtonComponent implements OnInit {
ngOnInit() {
// Initialize the SDK
init({
clientId: "web_demo_client_001", // Required
customerId: "cust-2201", // Optional
customerName: "Acme, Inc.", // Optional
// userId: 'user-8731', // Optional; omit for anonymous
autoCapture: true, // Optional (default: true)
debugLog: false, // Optional (default: false)
});
}

async trackEvent() {
cruxCustom("purchase_completed", {
productId: "SKU-123",
amount: 99.99,
currency: "USD",
});
}
}

Plain JavaScript

<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/@cruxstack/browser-sdk@latest/dist/browser.js"></script>
</head>
<body>
<button id="signupBtn">Sign Up</button>

<script>
// Initialize the SDK
init({
clientId: "web_demo_client_001", // Required
customerId: "cust-2201", // Optional
customerName: "Acme, Inc.", // Optional
// userId: 'user-8731', // Optional; omit for anonymous
autoCapture: true, // Optional (default: true)
debugLog: false, // Optional (default: false)
});

// Track button clicks
document.getElementById("signupBtn").addEventListener("click", async () => {
cruxCustom("purchase_completed", {
productId: "SKU-123",
amount: 99.99,
currency: "USD",
});
});
</script>
</body>
</html>

Event Tracking Patterns

User Journey Tracking

Browser SDK Example:

// User signup flow
cruxCustom("user_signup_started", {
source: "organic_search",
referrer: document.referrer,
});

cruxCustom("user_signup_completed", {
email: "[email protected]",
signupMethod: "email",
});

cruxCustom("user_onboarding_completed", {
stepsCompleted: 5,
timeSpent: 120000, // 2 minutes in ms
});

Node.js SDK Example:

// Server-side user journey
cruxTrack("user_signup", {
userId: "user123",
email: "[email protected]",
source: "organic_search",
});

cruxTrack("user_onboarding_completed", {
userId: "user123",
stepsCompleted: 5,
timeSpent: 120000,
});

cruxTrack("user_conversion", {
userId: "user123",
plan: "premium",
amount: 99.99,
});

E-commerce Tracking

Browser SDK - Product Interactions:

// Product view
cruxCustom("product_viewed", {
productId: "prod_456",
category: "electronics",
price: 299.99,
page: window.location.pathname,
});

// Add to cart
cruxCustom("cart_item_added", {
productId: "prod_456",
quantity: 1,
cartValue: 299.99,
});

// Checkout process
cruxCustom("checkout_started", {
cartValue: 299.99,
itemCount: 1,
});

Node.js SDK - Purchase Completion:

// Server-side purchase tracking
cruxTrack("purchase_completed", {
userId: "user123",
orderId: "order_789",
totalAmount: 299.99,
paymentMethod: "credit_card",
products: [{ productId: "prod_456", quantity: 1, price: 299.99 }],
});

Feature Usage Tracking

Browser SDK - Frontend Features:

// Feature activation
cruxCustom("feature_activated", {
featureName: "advanced_analytics",
activationMethod: "upgrade",
userAgent: navigator.userAgent,
});

// Feature usage with timing
const startTime = Date.now();
// ... user interacts with feature ...
const usageDuration = Date.now() - startTime;

cruxCustom("feature_used", {
featureName: "data_export",
usageDuration: usageDuration,
});

Node.js SDK - Backend Features:

// Server-side feature tracking
cruxTrack("feature_activated", {
userId: "user123",
featureName: "api_access",
activationMethod: "subscription",
});

cruxTrack("feature_used", {
userId: "user123",
featureName: "bulk_export",
usageDuration: 45000,
});

Best Practices

1. Consistent Event Naming

Use clear, descriptive event names across platforms:

  • user_signup_completed
  • product_purchase_initiated
  • event1
  • user_action

2. Structured Event Data

Include relevant context in your events:

Browser SDK:

cruxCustom("page_viewed", {
pageName: "dashboard",
referrer: document.referrer,
userAgent: navigator.userAgent,
viewport: {
width: window.innerWidth,
height: window.innerHeight,
},
});

Node.js SDK:

cruxTrack("api_request", {
userId: "user123",
endpoint: "/api/users",
method: "POST",
responseTime: 150,
statusCode: 200,
});

3. User Identification

Always include a consistent userId:

Browser SDK:

// Initialize with user ID
init({
clientId: "web_demo_client_001", // Required
customerId: "cust-2201", // Optional
customerName: "Acme, Inc.", // Optional
// userId: 'user-8731', // Optional; omit for anonymous
autoCapture: true, // Optional (default: true)
debugLog: false, // Optional (default: false)
});

// Track events (userId is automatically included)
cruxCustom("login", {});
cruxCustom("logout", {});

Node.js SDK:

// Good: Consistent user ID
cruxTrack("login", { userId: "user_12345" });
cruxTrack("logout", { userId: "user_12345" });

// Avoid: Inconsistent IDs
cruxTrack("login", { userId: "user_12345" });
cruxTrack("logout", { userId: "12345" }); // Different format

4. Error Handling

Browser SDK:

try {
cruxCustom("important_action", {
action: "critical_operation",
});
} catch (error) {
console.error("Failed to track event:", error);
// Handle gracefully - don't break user experience
}

Node.js SDK:

try {
cruxTrack("important_action", {
userId: "user123",
action: "critical_operation",
});
} catch (error) {
console.error("Failed to track event:", error);
// Handle gracefully - don't break user experience
}

Integration Examples

React Hook for Tracking

// useTracking.ts
import { useCallback } from "react";
import { init, cruxCustom } from "@cruxstack/browser-sdk";

export const useTracking = () => {
const trackEvent = useCallback(async (category: string, data: any) => {
try {
cruxCustom(category, {
...data,
timestamp: Date.now(),
page: window.location.pathname,
});
} catch (error) {
console.error("Failed to track event:", error);
}
}, []);

return { trackEvent };
};

// Usage in component
const { trackEvent } = useTracking();

const handleButtonClick = () => {
trackEvent("button_clicked", {
buttonName: "upgrade",
page: "pricing",
});
};

Express.js Middleware (Node.js)

import { cruxTrack } from "@cruxstack/node-sdk";

const trackingMiddleware = (req, res, next) => {
const userId = req.user?.id || req.headers["x-user-id"];

if (userId) {
cruxTrack("api_request", {
userId,
endpoint: req.path,
method: req.method,
userAgent: req.headers["user-agent"],
}).catch(console.error);
}

next();
};

app.use(trackingMiddleware);

Vue.js Plugin

// cruxstack-plugin.js
import { init } from "@cruxstack/node-sdk";

export default {
install(app, options) {
// Initialize SDK
init({
clientId: "cs_demo_client_001",
});

// Add global tracking method
app.config.globalProperties.$track = async (category, data) => {
cruxCustom(category, data);
};
},
};

// Usage in main.js
import CruxstackPlugin from "./cruxstack-plugin";

app.use(CruxstackPlugin, {
appId: "your-app-id",
userId: "user123",
});

// Usage in components
this.$track("button_clicked", { buttonName: "signup" });

Analytics & Insights

Understanding Your Data

Once you're tracking events, you can:

  1. Monitor User Engagement: Track feature usage and user activity patterns
  2. Identify Conversion Funnels: Follow users from signup to conversion
  3. Optimize User Experience: Identify drop-off points and friction areas
  4. Personalize Experiences: Use behavioral data for targeted features

Common Metrics to Track

  • User Activation: Time from signup to first meaningful action
  • Feature Adoption: Percentage of users using key features
  • Retention: User return rates over time
  • Conversion: Signup to paid conversion rates

Troubleshooting

Common Issues

Browser SDK:

  • "SDK not initialized": Make sure you call init() before tracking events
  • Events not sending: Check network connectivity and CORS settings
  • Auto-capture not working: Ensure autoCapture: true is set during initialization

Node.js SDK:

  • "SDK not initialized": Call init() before any tracking functions
  • Events stuck in queue: Check getQueueSize() and use clearQueue() if needed
  • Network errors: Events are automatically retried, check your API endpoint

Debug Mode

Enable debug logging during development:

Browser SDK:

init({
clientId: "web_demo_client_001", // Required
customerId: "cust-2201", // Optional
customerName: "Acme, Inc.", // Optional
// userId: 'user-8731', // Optional; omit for anonymous
autoCapture: true, // Optional (default: true)
debugLog: false, // Optional (default: false)
});

Node.js SDK:

init({
clientId: "cs_demo_client_001",
});

Next Steps