Skip to content

Guides

Comprehensive guides to help you make the most of our SDKs.

Getting Started

New to our SDKs? Start here:

Best Practices

Development Best Practices

Learn how to implement the SDK effectively:

API Key Management

javascript
// ❌ Don't hardcode API keys
const sdk = new SDK({ apiKey: "abc123def456" });

// ✅ Use environment variables
const sdk = new SDK({
  apiKey: process.env.SDK_API_KEY,
});

Error Handling

javascript
// ❌ Don't ignore errors
sdk.trackEvent("event", data);

// ✅ Handle errors gracefully
try {
  sdk.trackEvent("event", data);
} catch (error) {
  console.error("Tracking failed:", error);
  // Implement fallback or retry logic
}

Performance

javascript
// ❌ Don't track on every keystroke
input.addEventListener("keyup", () => {
  sdk.trackEvent("typing");
});

// ✅ Debounce frequent events
const debouncedTrack = debounce(() => {
  sdk.trackEvent("search_query", { query: input.value });
}, 500);

input.addEventListener("keyup", debouncedTrack);

Data Collection Best Practices

Event Naming

javascript
// ❌ Inconsistent naming
sdk.trackEvent("Button Click");
sdk.trackEvent("button-press");
sdk.trackEvent("BUTTONCLICKED");

// ✅ Consistent snake_case
sdk.trackEvent("button_clicked");
sdk.trackEvent("form_submitted");
sdk.trackEvent("video_played");

Event Properties

javascript
// ❌ Unclear properties
sdk.trackEvent("action", {
  val: 123,
  t: "xyz",
});

// ✅ Clear, descriptive properties
sdk.trackEvent("product_viewed", {
  product_id: "123",
  product_name: "Widget",
  category: "Electronics",
  price: 99.99,
  currency: "USD",
});

User Privacy

javascript
// ❌ Don't track PII without consent
sdk.setUser({
  email: "user@example.com",
  phone: "+1234567890",
  ssn: "123-45-6789",
});

// ✅ Hash or anonymize sensitive data
sdk.setUser({
  userId: hashUserId(user.id),
  role: user.role,
  subscription: user.plan,
});

Performance Optimization

Reduce Bundle Size

Web SDK

javascript
// ❌ Import everything
import SDK from "@your-org/web-sdk";

// ✅ Import only what you need
import { Analytics, Sentiments } from "@your-org/web-sdk/modules";

Lazy Loading

javascript
// Load SDK only when needed
button.addEventListener("click", async () => {
  const { default: SDK } = await import("@your-org/web-sdk");
  const sdk = new SDK(config);
  sdk.initialize();
});

Optimize Event Batching

javascript
const sdk = new SDK({
  apiKey: "key",

  // Optimize batching
  batchSize: 20, // Send when 20 events queued
  batchInterval: 10000, // Or every 10 seconds

  // Compress data
  compression: true,
});

Mobile Performance

iOS

swift
// Configure for optimal battery life
YourOrgSDK.configure(
    apiKey: "key",
    configuration: SDKConfiguration(
        batchSize: 15,
        batchInterval: 30.0,        // 30 seconds
        trackInBackground: false,   // Save battery
        locationTracking: false     // Disable if not needed
    )
)

Android

kotlin
YourOrgSDK.configure(
    context = applicationContext,
    apiKey = "key",
    configuration = SDKConfiguration(
        batchSize = 15,
        batchInterval = 30_000L,    // 30 seconds
        wakeOnBatch = false,        // Don't wake device
        useWorkManager = true       // Better battery handling
    )
)

Security Guidelines

API Key Security

Never Expose API Keys

Never commit API keys to public repositories or expose them in client-side code.

Environment Variables

bash
# .env
SDK_API_KEY=your-production-key
SDK_TEST_KEY=your-test-key

Key Rotation

javascript
// Implement graceful key rotation
const sdk = new SDK({
  apiKey: getCurrentAPIKey(),
  onAuthError: async () => {
    const newKey = await fetchNewKey();
    sdk.updateAPIKey(newKey);
  },
});

Data Security

Encrypt Sensitive Data

javascript
// Before sending sensitive data
sdk.trackEvent("purchase", {
  order_id: orderId,
  total: encryptValue(total),
  items: items.map((item) => ({
    id: item.id,
    // Don't send credit card info
  })),
});

HTTPS Only

javascript
// ✅ Always use HTTPS
const sdk = new SDK({
  apiKey: "key",
  apiEndpoint: "https://api.yourorg.com", // Not http://
});

Privacy Compliance

GDPR Compliance

javascript
// Respect user consent
if (userHasConsented) {
  sdk.initialize();
  sdk.setUser({ userId: user.id });
} else {
  // Don't initialize or track
  console.log("User has not consented to tracking");
}

// Allow users to opt-out
function handleOptOut() {
  sdk.optOut();
  sdk.deleteUserData(userId);
}

Data Minimization

javascript
// ❌ Collect everything
sdk.trackEvent("page_view", {
  url: location.href,
  referrer: document.referrer,
  user_agent: navigator.userAgent,
  screen: screen,
  cookies: document.cookie, // Don't!
  localStorage: { ...localStorage }, // Don't!
});

// ✅ Collect only what you need
sdk.trackEvent("page_view", {
  page: location.pathname,
  title: document.title,
});

Testing Guidelines

Test in Development

javascript
// Use test environment during development
const sdk = new SDK({
  apiKey: process.env.SDK_TEST_KEY,
  environment: "test",
  debugMode: true,
  verboseLogging: true,
});

Verify Events

javascript
// Enable debug mode to see events
sdk.on("event_tracked", (event) => {
  console.log("Event tracked:", event);
});

sdk.on("event_failed", (error) => {
  console.error("Event failed:", error);
});

Unit Testing

Mock the SDK in tests:

javascript
// __mocks__/@your-org/web-sdk.js
export default class MockSDK {
  constructor(config) {
    this.config = config;
    this.events = [];
  }

  initialize() {
    return Promise.resolve();
  }

  trackEvent(name, data) {
    this.events.push({ name, data });
  }
}

// your-component.test.js
jest.mock("@your-org/web-sdk");

test("tracks click event", () => {
  const sdk = new SDK({ apiKey: "test" });
  // Test your code
  expect(sdk.events).toContainEqual({
    name: "button_clicked",
    data: { button_id: "submit" },
  });
});

Multi-Environment Setup

Development, Staging, Production

javascript
const environments = {
  development: {
    apiKey: "dev-key",
    environment: "test",
    debugMode: true,
  },
  staging: {
    apiKey: "staging-key",
    environment: "test",
    debugMode: false,
  },
  production: {
    apiKey: "prod-key",
    environment: "production",
    debugMode: false,
  },
};

const config = environments[process.env.NODE_ENV] || environments.development;
const sdk = new SDK(config);

Troubleshooting

Debug Mode

Enable detailed logging:

javascript
const sdk = new SDK({
  apiKey: "key",
  debugMode: true,
  verboseLogging: true,
});

// Check SDK status
sdk.getStatus().then((status) => {
  console.log("SDK Status:", status);
});

Common Issues

Events Not Appearing

  1. Check API key is correct
  2. Verify environment (test vs production)
  3. Check network tab for failed requests
  4. Enable debug mode
  5. Verify domain is whitelisted

Performance Issues

  1. Check batch settings
  2. Reduce event frequency
  3. Use lazy loading
  4. Check bundle size

Advanced Topics

Custom Analytics Pipeline

Integrate with your own analytics:

javascript
sdk.on("event_tracked", (event) => {
  // Send to your analytics
  yourAnalytics.track(event.name, event.data);

  // Send to multiple destinations
  googleAnalytics.track(event);
  segmentAnalytics.track(event);
});

Server-Side Tracking

Use server-side SDK for sensitive operations:

javascript
// Server-side (Node.js)
const { ServerSDK } = require("@your-org/server-sdk");

const sdk = new ServerSDK({
  apiKey: process.env.SDK_SECRET_KEY,
  environment: "production",
});

app.post("/api/purchase", async (req, res) => {
  // Track server-side
  await sdk.trackEvent("purchase", {
    userId: req.user.id,
    orderId: order.id,
    total: order.total,
  });

  res.json({ success: true });
});

Resources

Need Help?

Released under the MIT License.