Optimizely Edge Delivery lets you execute Optimizely Web experiments on Cloudflare Workers.
- You must have a Cloudflare Account.
- You must install the Wrangler CLI.
#TODO: turn this into a cloudflare worker template instead
To get started quickly with a new project:
-
Clone this repository and navigate to the templates/edge-delivery-starter directory
cd templates/edge-delivery-starter
-
Install requirements
npm install
-
Run the worker locally
npm run dev
This will open your worker executing in a browser. This loads the website https://example.com/ and executes an experiment that modifies the
h1
header text on the edge. -
Modify the
SNIPPET_ID
andDEV_URL
environment variables in the in the wrangler.toml file. In this project, these are set to an example Optimizely Web Experiment by default. Modify these to your to test an Optimizely Web Experiment against your own website.- Run
npm run dev
again to test the changes.
- Run
-
Log in to your Cloudflare account using OAuth
wrangler login
-
Deploy the worker to your Cloudflare account:
npm run deploy
-
On Cloudflare, add a route for your worker for the target website you want to proxy
- Alternatively, you can do this by adding a route to the wrangler.toml before running
npm run deploy
.
- Alternatively, you can do this by adding a route to the wrangler.toml before running
-
Navigate to your website in a browser, and see your experiments in action!
You can install the Optimizely Edge Delivery SDK in any existing Cloudflare Worker, whether you already route your incoming traffic through a Cloudflare Worker, or you'd prefer to start from scratch using Cloudflare's getting started guide.
To install the Edge Delivery library, download and install the latest version of the edge-delivery npm package:
npm install @optimizely/edge-delivery@latest
The SDK requires a Snippet ID (snippetId
) to know which configuration file to retrieve to execute your experiments.
It's recommended to set a Development URL (devUrl
) for the SDK to use as a target when testing locally or at your worker site directly.
const options = {
"snippetId": "29061560280",
"devUrl": "https://example.com/"
};
The applyExperiments
method is used to execute experiments. This method uses the request information to make experiment bucketing decisions and apply active experiment variations to the control. Any decisions or changes that cannot be made on the edge are packaged together and added to the <head>
element for execution on the browser.
import { applyExperiments } from '@optimizely/edge-delivery';
...
await applyExperiments(request, ctx, options);
Optionally, you may pass a Response object as the control in the options
parameter. This can be useful if you already have an existing Cloudflare Worker that, for example, makes modifications to the control outside of Optimizely experiments.
let control = await fetch(request);
...
const options = {
// Other options
"control": control
};