This project demonstrates how to integrate Flagship feature flags with Cloudflare Workers, enabling feature flagging and A/B testing at the edge.
This example shows how to:
- Initialize the Flagship SDK in a Cloudflare Worker
- Use KV storage for caching bucketing data to improve performance
- Extract visitor context from request headers
- Fetch and apply feature flags for each visitor
- Send analytics data back to Flagship
The worker performs the following operations:
- Retrieves Flagship credentials from environment variables
- Loads cached bucketing data from Cloudflare KV storage
- Initializes the Flagship SDK in edge bucketing mode
- Creates a visitor with context data from request headers
- Fetches feature flags for the visitor
- Flushes analytics data back to Flagship
- Returns flag values in a JSON response
- Node.js (v18 or later)
- Yarn (v4 or later)
- A Cloudflare account
- A Flagship account with API credentials
- Clone this repository:
git clone https://github.com/flagship-io/flagship-cloudflare-worker-example.git
cd flagship-cloudflare-worker-example- Install dependencies:
yarn install- Configure your Flagship credentials as Cloudflare Worker secrets:
wrangler secret put FLAGSHIP_ENV_ID
wrangler secret put FLAGSHIP_API_KEY- Create a KV namespace for caching:
wrangler kv:namespace create MY_APP_KV- Update the wrangler.jsonc file with your KV namespace ID
Bucketing data contains information about your Flagship campaigns and variations, allowing the worker to make flag decisions at the edge without calling the Flagship API for every request.
- Fetch bucketing data directly from the Flagship CDN:
# Replace YOUR_ENV_ID with your Flagship Environment ID
curl -s https://cdn.flagship.io/YOUR_ENV_ID/bucketing.json > bucketing-data.json- Upload the bucketing data to your KV namespace:
wrangler kv:key put --binding=MY_APP_KV "initialBucketing" "$(cat bucketing-data.json)"For direct integration, you'll need to:
- Fetch the bucketing data during your build process
- Save it as a JSON file in your project
- Import it directly in your worker code
# During build/deployment:
curl -s https://cdn.flagship.io/YOUR_ENV_ID/bucketing.json > src/bucketing-data.jsonThen import in your code:
import bucketingData from './bucketing-data.json';
// Use this data when initializing FlagshipFor production environments, there are two recommended approaches. Both require setting up webhooks in the Flagship platform that trigger your CI/CD pipeline when campaigns are updated. Find more details in the Flagship documentation.
Start a local development server:
yarn devDeploy to Cloudflare:
yarn deployThis example is provided for educational purposes.