@testit-sdk/express
v1.0.2
Published
An A/B testing utility for Express applications.
Downloads
10
Readme
AbTest
AbTest is a lightweight TypeScript library for implementing A/B testing in Express.js applications. It provides an easy way to create and manage experiments, assign users to variants, and check variant assignments. This package is made to work with Test It but can be used without it if you have your own analytics system.
Features
- Simple API for creating and managing A/B tests
- Supports multiple experiments and variants
- Persistent variant assignment using cookies
- Weighted random selection of variants
- TypeScript support
Installation
npm install @testit-sdk/express
Usage
Basic Example
import AbTest from "@testit-sdk/express";
import express from "express";
const app = express();
app.get("/", (req, res) => {
const abTest = new AbTest({
experimentId: "66d6381d630d87321d2937c6",
variants: [
{ id: "66d6621d630d87341d2937f3", name: "baseline", weight: 50 },
{ id: "66d6681c630d87341d2936d4", name: "v_1", weight: 50 },
],
req,
res,
});
if (abTest.isVariant("v_1")) {
res.send('<button style="background-color: blue;">Click me!</button>');
} else {
res.send('<button style="background-color: red;">Click me!</button>');
}
});
app.listen(3000, () => console.log("Server running on port 3000"));
API
Constructor
options.experimentId
: Unique identifier for the experimentoptions.variants
: Array of variant objects withid
,name
, andweight
propertiesoptions.req
: Express request objectoptions.res
: Express response object
Methods
isVariant(variantName: string): boolean
: Check if the current user is assigned to a specific variantisV(variantName: string): boolean
: Alias forisVariant
How It Works
AbTest uses cookies to persistently assign users to variants. When a user first encounters an experiment, they are randomly assigned to a variant based on the specified weights. This assignment is stored in a cookie and reused for subsequent requests.