LeveredDocs
Manual Setup

5. Integrate the SDK

Install the JavaScript SDK, serve variants to users, and log exposure events to your warehouse.

The Levered SDK requests a variant assignment from the Levered API and returns the values to render. The SDK does not log exposures. Log each exposure event to your data warehouse, so that Levered can join the exposures with the reward data at training time.

Install

npm install @levered_dev/sdk

React integration

Set up the provider

Wrap the application, or the subtree that uses variants, with LeveredProvider. The provider initializes the SDK client and makes the variant hooks available to child components.

import { LeveredProvider } from '@levered_dev/sdk/react';

function App() {
  return (
    <LeveredProvider
      apiUrl="https://api.levered.dev"
      anonymousId={getUserId()}
      onExposure={(exposure) => {
        // Log the exposure to your warehouse
        analytics.track('levered_exposure', {
          optimization_id: exposure.optimizationId,
          anonymous_id: exposure.anonymousId,
          variant: exposure.variant,
          timestamp: exposure.timestamp,
        });
      }}
    >
      <YourApp />
    </LeveredProvider>
  );
}

Key props:

PropRequiredDescription
apiUrlYesThe Levered API endpoint. Use https://api.levered.dev for production.
anonymousIdYesA stable user identifier. It must match the anonymous_id in the metric queries.
onExposureNoCallback that the SDK calls when a variant is assigned. Log this event to your warehouse. Without logged exposures, the model has no exposure data to learn from.

Use variants in components

The useVariant hook fetches the assigned variant for an optimization. Pass a fallback. The component renders the fallback values while the SDK loads the variant.

import { useVariant } from '@levered_dev/sdk/react';

function HeroSection() {
  const { variant, isLoading } = useVariant({
    optimizationId: 'your-optimization-id',
    fallback: { headline: 'Welcome', cta_text: 'Sign Up' },
  });

  return (
    <section>
      <h1>{variant.headline}</h1>
      <button>{variant.cta_text}</button>
    </section>
  );
}

The variant object contains one key per design factor, with the assigned level as the value. While the SDK loads, variant contains the fallback values, which avoids a layout shift.

Full React example

import { LeveredProvider } from '@levered_dev/sdk/react';
import { useVariant } from '@levered_dev/sdk/react';

function HeroSection() {
  const { variant, isLoading } = useVariant({
    optimizationId: '699ede80-c94b-4f98-9c79-dd3e07748703',
    fallback: { headline: 'Ship faster', cta_text: 'Start free' },
  });

  return (
    <section className="hero">
      <h1>{variant.headline}</h1>
      <p>Build and release your product in one place.</p>
      <button className="cta">{variant.cta_text}</button>
    </section>
  );
}

export default function App() {
  return (
    <LeveredProvider
      apiUrl="https://api.levered.dev"
      anonymousId={getUserId()}
      onExposure={(e) => analytics.track('levered_exposure', e)}
    >
      <HeroSection />
    </LeveredProvider>
  );
}

Vanilla JavaScript

Without React, use LeveredClient directly.

import { LeveredClient } from '@levered_dev/sdk';

const FALLBACK = { headline: 'Welcome', cta_text: 'Sign Up' };

const client = new LeveredClient({
  apiUrl: 'https://api.levered.dev',
  onExposure: (event) => {
    // Log the exposure to your warehouse
    analytics.track('levered_exposure', {
      anonymous_id: event.anonymousId,
      timestamp: event.timestamp,
      optimization_id: event.optimizationId,
      variant: event.variant,
      context: event.context,
      is_holdout: event.isHoldout,
      trained: event.trained,
    });
  },
});

// Get a variant assignment
const result = await client.getVariant({
  anonymousId: getUserId(),
  optimizationId: 'your-optimization-id',
});

// Use the variant values (fall back if null)
const variant = result?.variant ?? FALLBACK;
document.querySelector('h1').textContent = variant.headline;
document.querySelector('.cta').textContent = variant.cta_text;

Logging exposures

The SDK does not log exposures. The destination of the exposures depends on the warehouse:

  • Data warehouse native. Log exposures to your own warehouse through your existing pipeline.
  • Managed Warehouse. Send exposures from your server to the ingestion API. Keep the API key on the server.

An exposure event contains at least the following fields:

FieldDescription
optimization_idThe optimization that the variant came from.
anonymous_idThe id passed to the SDK as anonymousId. The reward metric must return the same id.
variantThe full variant assignment, with one value per design factor.
timestampThe time of the exposure.
is_holdouttrue if the user is in the holdout. This field is recommended. Levered computes lift from the id and does not need this column. The column is useful for your own analysis of the holdout, and levered verify uses it to check the id column.

Log exposures in the onExposure callback. Both LeveredProvider (React) and LeveredClient (vanilla JS) accept it. With your own warehouse, use your existing pipeline, for example Segment, Rudderstack, or a direct BigQuery or Snowflake insert.

Context factors

If the optimization has context factors, pass their values when requesting a variant:

const { variant } = useVariant({
  optimizationId: 'your-optimization-id',
  fallback: { headline: 'Welcome', cta_text: 'Sign Up' },
  context: {
    device_type: 'mobile',
    country: 'US',
  },
});

The model uses the context values to select a variant for each user segment.

Server-side usage

To request variants from a backend, call the REST API:

curl -X POST https://api.levered.dev/api/v2/optimizations/{id}/serve \
  -H "Authorization: Bearer $LEVERED_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "anonymous_id": "user_abc123",
    "context": {"device_type": "mobile"}
  }'

Use the REST API for server-rendered pages, email personalization and other non-browser environments.

Verifying the integration

Dry-run requests

A dry-run call to /serve confirms that the SDK is connected. With "dry_run": true, the request runs through the decision path of a real serve and returns a real variant payload. For a draft, live or paused optimization, that path is holdout bucketing and inference. For a shipped optimization, the request returns the shipped variant for the context, without holdout bucketing or inference. The response has the same shape as the response of a real serve.

Levered does not record a dry-run request:

  • No serve event is written.
  • No sticky-variant lookup runs.
  • Auto-training is not triggered.

The tracking of the app is not affected. If the app logs the exposure, the row is written to your warehouse. Use this to test the whole pipeline before launch (Test before launch).

curl -X POST https://api.levered.dev/api/v2/optimizations/{id}/serve \
  -H "Authorization: Bearer $LEVERED_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "anonymous_id": "test-user-1",
    "dry_run": true
  }'

A 200 OK response with a variants array means that the request reached Levered and returned a variant. Use the same call in CI, in smoke tests or as a local curl command to check the integration without writing to metrics.

dry_run: true is allowed on optimizations with status draft, live, paused and shipped. For these states it bypasses the usual status check of /serve. They cover the time before launch (draft), while serving (live, shipped) and after a temporary stop (paused). For the terminal states completed and archived, the request returns 400 "Dry-run is only allowed on draft, live, paused, or shipped optimizations (status: <status>)".

The first /serve call that Levered receives for an optimization, dry-run or not, completes the SDK connected step under Required on the Setup tab of the optimization. The tab shows these steps while the optimization is a draft. A draft can then be started with Start optimizing. A dry-run is not recorded as an exposure.

Other checks

  1. Dashboard. The optimization detail page shows exposure counts after events are in your warehouse and the model has trained.
  2. Metric preview. Run levered metrics preview <metric-uuid> and check that it returns reward rows.
  3. Warehouse tables. Query the exposure and reward tables and check that the events arrive.

Next steps

  • Test before launch describes how to check the user id, try the holdout with test users and confirm that test events arrive.
  • SDK Reference documents the full API of the JavaScript SDK.
  • Concepts: Optimizations explains how optimizations, the model and training work.
  • CLI Reference lists the commands for managing Levered from the terminal.
  • API Reference lists the REST API endpoints for server-side integration.