npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@denismartins/abtest-sdk

v1.1.6

Published

A/B Testing SDK for React applications - Self-hosted solution with SSR support

Readme

A/B Testing SDK

A production-ready React hook for A/B testing with your self-hosted A/B testing platform.

Features

  • 🚀 Production Ready: Built for real-world applications with error handling and fallbacks
  • 🎯 Self-Hosted: Works with your own A/B testing server
  • 📊 Event Tracking: Built-in success and custom event tracking
  • 🔄 Offline Support: Graceful degradation when server is unavailable
  • 🎲 Weighted Variations: Support for complex traffic allocation
  • 📱 React Native Compatible: Works in both web and mobile environments
  • 🛡️ TypeScript: Full type safety and IntelliSense support
  • 🐛 Debug Mode: Comprehensive logging for development
  • 🔐 Login Sync: Automatically syncs variations when users log in after being assigned a variation

Installation

npm install @abtest/sdk

Quick Start

1. Configure the SDK

import { useExperiment, ABTestConfig } from "@abtest/sdk";

const config: ABTestConfig = {
  apiUrl: "http://localhost:3001/api", // Your self-hosted API URL
  userId: "user-123", // Optional: for user-based experiments
  environment: "production", // Optional: development, staging, production
  debug: false, // Optional: enable debug logging
  fallback: "control", // Optional: fallback variation
  timeout: 5000, // Optional: API timeout in ms
};

2. Use the Hook

import React from "react";
import { useExperiment } from "@abtest/sdk";

const ButtonExperiment = () => {
  // Simply provide the experiment ID - the hook will fetch experiment details automatically
  const { variation, isLoading, error, trackSuccess, experiment } =
    useExperiment(
      "button-color-test", // Experiment ID from your dashboard
      config
    );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  const handleClick = () => {
    // Track success when user clicks the button
    trackSuccess({ buttonColor: variation });
  };

  return (
    <button
      onClick={handleClick}
      style={{ backgroundColor: variation === "blue" ? "#007bff" : "#dc3545" }}
    >
      Click me!
    </button>
  );
};

API Reference

useExperiment(experiment, config)

The main hook for A/B testing.

Parameters

  • experiment (Experiment): The experiment configuration
  • config (ABTestConfig): SDK configuration

Returns

  • variation (string | null): Current variation name
  • isLoading (boolean): Whether the experiment is loading
  • error (Error | null): Any error that occurred
  • source (string): Source of the variation (localStorage, cookie, backend, generated, fallback)
  • isActive (boolean): Whether the experiment is active
  • metadata (object): Experiment metadata
  • trackSuccess (function): Track a success event

ABTestConfig

Configuration object for the SDK.

interface ABTestConfig {
  apiUrl: string; // Required: Your self-hosted API URL
  userId?: string; // Optional: User ID for user-based experiments
  sessionId?: string; // Optional: Session ID for session-based experiments
  environment?: "development" | "staging" | "production"; // Optional: Environment
  debug?: boolean; // Optional: Enable debug logging
  fallback?: string; // Optional: Fallback variation when experiment fails
  randomFn?: () => number; // Optional: Custom random function for testing
  timeout?: number; // Optional: API timeout in ms (default: 5000)
}

Experiment

Experiment configuration object.

interface Experiment {
  id: string; // Unique experiment ID
  name: string; // Experiment name
  variations: Variation[]; // Array of variations
  version?: string; // Optional: Experiment version
  description?: string; // Optional: Experiment description
  startDate?: string; // Optional: Start date (ISO string)
  endDate?: string; // Optional: End date (ISO string)
  isActive?: boolean; // Optional: Whether experiment is active
  successMetric?: {
    // Optional: Success metric configuration
    type: "click" | "conversion" | "custom";
    target?: string;
    value?: string;
  };
}

Variation

Variation configuration object.

interface Variation {
  name: string; // Variation name
  weight: number; // Traffic weight (0-1)
  isBaseline?: boolean; // Whether this is the baseline variation
}

Event Tracking

Track Success Events

const { trackSuccess } = useExperiment(experiment, config);

// Track a success event
await trackSuccess({
  conversionValue: 29.99,
  productId: "product-123",
});

Track Custom Events

const { trackSuccess } = useExperiment(experiment, config);

// Track a custom event as a success event
await trackSuccess({
  event: "page_view",
  value: 1,
  page: "/checkout",
  timeOnPage: 120,
});

Login Sync

The SDK automatically handles the scenario where a user visits a page without being logged in, gets assigned a variation, and then logs in later:

// User visits page without userId
const configWithoutUser = {
  apiUrl: "http://localhost:3001/api",
  // userId: undefined (not logged in)
};

const { variation } = useExperiment("button-test", configWithoutUser);
// variation: "blue" (stored in localStorage only)

// User logs in - userId becomes available
const configWithUser = {
  apiUrl: "http://localhost:3001/api",
  userId: "user-123", // User just logged in
};

// The hook automatically:
// 1. Detects userId change
// 2. Syncs localStorage variation to backend
// 3. Or uses existing backend variation if user already has one

Advanced Usage

Custom Random Function

For testing or deterministic behavior:

const config: ABTestConfig = {
  apiUrl: "http://localhost:3001/api",
  randomFn: () => 0.3, // Always returns 30% for testing
};

Environment-Specific Configuration

const config: ABTestConfig = {
  apiUrl: process.env.REACT_APP_ABTEST_API_URL || "http://localhost:3001/api",
  environment: process.env.NODE_ENV as "development" | "staging" | "production",
  debug: process.env.NODE_ENV === "development",
};

Error Handling

const { variation, error, isLoading } = useExperiment(experiment, config);

if (error) {
  // Handle error - show fallback UI
  return <FallbackComponent />;
}

if (isLoading) {
  // Show loading state
  return <LoadingSpinner />;
}

// Use variation
return <ExperimentComponent variation={variation} />;

Self-Hosted Setup

This SDK works with the self-hosted A/B testing platform. To set up your own server:

  1. Deploy the Backend: Follow the deployment guide in the main repository
  2. Configure API URL: Point the SDK to your server's API endpoint
  3. Set up Experiments: Use the dashboard to create and manage experiments

Browser Support

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

React Native Support

The SDK works in React Native environments. Make sure to:

  1. Install the required dependencies
  2. Configure the API URL for your mobile app
  3. Handle network connectivity gracefully

Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

License

MIT License - see LICENSE file for details.

Support

For support and questions: