Set up an A/B Test at The Edge
A/B tests are a great way to test new features on your site. A basic A/B test works by assigning visitors to a particular test "bucket" the first time they visit a site, usually using a random number between 0 and 1.
Visitors can then be redirected to different pages, depending on the bucket and cookie they were assigned.
You could even use A/B testing in combination with Geolocation at The Edge!
import type { Context } from "netlify:edge";
export default async (request: Request, context: Context) => {
// look for existing "test_bucket" cookie
const bucketName = "test_bucket";
const bucket = context.cookies.get(bucketName);
// return here if we find a cookie
if (bucket) {
return new Response(`${bucketName} ${bucket} already assigned!`);
}
// if no "test_bucket" cookie is found, assign the user to a bucket
// in this example we're using two buckets (a, b) with an equal weighting of 50/50
const weighting = 0.5;
// get a random number between (0-1)
// this is a basic example and you may want to experiment
const random = Math.random();
const newBucketValue = random <= weighting ? "a" : "b";
// set the new "test_bucket" cookie
context.cookies.set({
name: bucketName,
value: newBucketValue,
});
return new Response(
`You have been assigned ${bucketName} ${newBucketValue}.`,
);
};
See this in action
- Run the A/B test code, and see which bucket you were assigned!
- The Edge Function code: abtest.ts
Related
What are Edge Functions?
Using JavaScript and TypeScript, Netlify Edge Functions give you the power to modify network requests to localize content, serve relevant ads, authenticate visitors, A/B test content, and much more! And this all happens at the Edge — directly from the worldwide location closest to each user.
To use Edge Functions on Netlify, add JavaScript or TypeScript files to an edge-functions directory in your project, and add [[edge_functions]]
entries to your netlify.toml file.
Deploy this site to Netlify
Try out Edge Functions on Netlify today! Click the button below to deploy this site with all of its demos to your Netlify account.
Deploy to Netlify