Middleware for AB/split/multi-variant testing in Express. Allows you to specify multiple variants of an endpoint as a part of an experiment. Remembers which variant the user was assigned using a cookie.
Supports outputting Google Experiments variables (
$ npm install express-ab --save
Notice that express-ab requires the cookie-parser middleware to remember which variant the user was served.
var express = ;var cookieParser = ;var ab = ;var app = ;app;var myPageTest = ab;app;app;app;
In example above users will be presented with either 'variant A' or 'variant B'. Distribution will be 50/50 in a round-robin fashion.
You can add as many alternative endpoints to your test as you like, e.g. also 'variant C' etc.
The function returned by
ab.test() (assigned to
myPageTest), has the following arguments:
If you prefer to have a custom distribution, you can specify a weight percentage for each variant. This should be in decimal notation, and the sum should be 1.
In this example variant A will be selected 20% of the time, and variant B 80% of the time.
If you are using Google Experiments you can add the expriment ID when running the test, and it will be available in the
locals collection like this:
var myPageTest = ab;app;
To use it in your front end, you can expose the
ab object e.g. on
window. Then you have to notify Google Analytics that you are running an experiment by setting the following vars:
ga('set', 'expId', window.ab.id); ga('set', 'expVar', window.ab.variantId);
More about setting the experiment variant in Google Analytics is explained here.
Get variant in other routes
If you need the selected variant in other routes not specifically part of the AB test, you can use the middleware function
getVariant() on the returned test function (assigned to
Usage as passive middleware
If you need the variant information in many routes in your application, and need cookies to be assigned for any/all of them, you can create your variants as general purpose middleware instead of attaching it to specific routes.
var variants = 'A' 'B' 'C';for var i = 0; i < variantslength; i++app;app;
If you do not want the user to be sent to the same variant in the test on every return, you can disable cookies like this:
var myPageTest = ab;
Or you can do it for all tests in the constructor:
var ab = cookie: false ;
Skip route if part of another test
If you are running multiple tests, you can skip routes using
ab.filter(test). To create a new test only for users not in the previous test, the code could look something like this:
var abTest1 = ab;var abTest2 = ab;app;app;app;
In this case, if a user is already in
abTest1, he will not be able to be in
abTest2 as well. Just remember to include a fall through route.