Vanilla JavaScript
The LeveredClient class for Node.js, Vue, Svelte, server-side handlers and other JavaScript environments without React.
The vanilla integration is the LeveredClient class. It runs in JavaScript and TypeScript environments, including the browser, Node.js, edge runtimes and server-side frameworks. Use it in an app without React, or if the app has to control when variants are fetched.
import { LeveredClient } from '@levered_dev/sdk';LeveredClient
Create a client instance with the API URL and the callbacks. The client handles retries, timeouts and in-memory caching.
import { LeveredClient } from '@levered_dev/sdk';
const client = new LeveredClient({
apiUrl: 'https://api.levered.dev',
onExposure: (event) => logToWarehouse(event),
onError: (err) => console.error('Levered error:', err),
timeoutMs: 2000,
maxRetries: 2,
cacheTtlMs: 60000,
});ClientConfig
| Option | Type | Default | Description |
|---|---|---|---|
apiUrl | string | None | Base URL of the Levered API (required). |
onExposure | (event: ExposureEvent) => void | None | Called when a variant is served to a user. Log the exposure event to the warehouse in this callback. |
onError | (error: unknown) => void | None | Called when a variant request fails with a network error or timeout after all retries. Not called for non-200 responses. Use it for monitoring. |
timeoutMs | number | 2000 | Request timeout in milliseconds. |
maxRetries | number | 2 | Number of retry attempts after a network failure. The client uses exponential backoff with a base of 200ms. |
cacheTtlMs | number | 60000 | Time in milliseconds that the client caches a variant response in memory. Set to 0 to disable caching. |
getVariant
getVariant requests one variant, which the optimization policy selects for the user. The SDK returns the design-factor values of the selected variant in result.variant.
const result = await client.getVariant({
anonymousId: 'user-123',
optimizationId: 'abc-123',
context: { country: 'US' },
});
if (result) {
renderPage(result.variant);
} else {
renderPage(fallbackVariant);
}Options
| Option | Type | Required | Description |
|---|---|---|---|
anonymousId | string | Yes | Stable anonymous identifier of the user or session. |
optimizationId | string | Yes | UUID of the optimization to serve variants from. |
context | Record<string, unknown> | No | Context values for the context factors of the optimization. |
Return value
getVariant returns VariantResult | null.
Each successful request selects one variant. The SDK sends no variant-count field and adapts the API's one-element variants array to result.variant.
- On success,
getVariantreturns an object withvariant(the design-factor values) andoptimizationId. - On an error (network failure, timeout or non-200 response), it returns
null. - If the API returns no variant, it returns a result whose
variantis{}. The client does not cache this result and does not callonExposurefor it.
interface VariantResult {
variant: Record<string, string | number | boolean>;
optimizationId: string;
optimizationName?: string;
isHoldout: boolean;
trained: boolean;
}The vanilla client has no fallback option. If the result is null, render a default variant that the app defines.
ExposureEvent
The client calls the onExposure callback with this event once for each API response that contains a variant. The client does not call it for a result from the cache, for a call that joins an identical request already in flight, for a result whose variant is {}, or on an error:
interface ExposureEvent {
anonymousId: string;
optimizationId: string;
optimizationName?: string;
variant: Record<string, string | number | boolean>;
context: Record<string, unknown>;
timestamp: string; // ISO-8601
isHoldout: boolean;
trained: boolean;
}Forward this event to the data warehouse. Levered reads the exposure data from the warehouse to train the model. If exposures are not logged, the model cannot be trained.
Server-side usage
The client uses the standard fetch API and runs in server-side environments such as Express, Fastify and Next.js API routes. The runtime has to support fetch. Node.js 18 and later have it built in. On other runtimes, use a polyfill.
Express example
import express from 'express';
import { LeveredClient } from '@levered_dev/sdk';
const app = express();
const levered = new LeveredClient({
apiUrl: 'https://api.levered.dev',
onExposure: (event) => {
// Write to your exposure table or send to a queue
insertExposure(event);
},
});
const FALLBACK = { headline: 'Welcome', cta_text: 'Get Started' };
app.get('/', async (req, res) => {
const anonymousId = req.cookies.session_id ?? generateId();
const result = await levered.getVariant({
anonymousId,
optimizationId: 'abc-123',
context: { country: req.headers['cf-ipcountry'] ?? 'US' },
});
const variant = result?.variant ?? FALLBACK;
res.render('home', { headline: variant.headline, cta: variant.cta_text });
});
app.listen(3000);Fastify example
import Fastify from 'fastify';
import { LeveredClient } from '@levered_dev/sdk';
const fastify = Fastify();
const levered = new LeveredClient({
apiUrl: 'https://api.levered.dev',
onExposure: (event) => insertExposure(event),
timeoutMs: 1500,
});
const FALLBACK = { headline: 'Welcome', cta_text: 'Get Started' };
fastify.get('/', async (request, reply) => {
const anonymousId = request.cookies.session_id ?? generateId();
const result = await levered.getVariant({
anonymousId,
optimizationId: 'abc-123',
});
return {
headline: result?.variant.headline ?? FALLBACK.headline,
cta_text: result?.variant.cta_text ?? FALLBACK.cta_text,
};
});
fastify.listen({ port: 3000 });Caching behavior
The client caches variant responses in memory. The cache key is the combination of optimizationId, anonymousId and context. Until a cached response expires, the client returns it without a network request.
- The default TTL is 60 seconds (
cacheTtlMs: 60000). - Set
cacheTtlMs: 0to disable caching. - Each client instance has its own in-memory cache. If the client is created at module scope on a server, all requests in the same process share the cache.
Error handling
getVariant does not throw. The client handles a failed request as follows:
- After a network error or a timeout, the client retries up to
maxRetriestimes with exponential backoff. If all attempts fail, it calls theonErrorcallback, if one is set, and returnsnull. - After a non-200 response, the client returns
nullwithout a retry and without callingonError.
The app has to check the result for null:
const result = await client.getVariant({ anonymousId, optimizationId });
const variant = result?.variant ?? fallback;