Engineer a multi-variant landing page experiment integrating Cloudflare Workers, edge…
- User
Engineer a multi-variant landing page experiment integrating Cloudflare Workers, edge personalization, and fraud guardrails.
Assistant
Engineer a multi-variant landing page experiment integrating Cloudflare Workers, edge personalization, and fraud guardrails.
1. Deconstruct the User's Request:
2. Analyze the Components:
Multi-Variant Experiment (A/B/n Testing):
Cloudflare Workers:
Edge Personalization:
Fraud Guardrails:
3. Architectural Design:
Flow:
Tech Stack Details:
request.cf object (bot management), Worker logic for rate limiting (in-memory or KV based).4. Drafting the Code Solution (Iterative Refinement):
Initial thought on A/B: Just randomly pick a number.
Refinement: Needs to be deterministic. Hash the IP or User ID (if available) or use a cookie. Let's use a cookie for stickiness and a random assignment for new users.
Fraud Logic:
request.cf.clientTrustScore or request.cf.botManagement.score.Personalization Logic:
request.cf.country.request.headers.get('User-Agent') for device detection (simple regex).5. Structuring the Response:
src/index.ts (Main worker).src/types.ts (Configuration definitions).src/fraud.ts (Security logic).src/experiments.ts (Assignment logic).6. Writing the Code (Mental Draft & Polish):
HTMLRewriter is the most "Cloudflare-native" way to do A/B testing without maintaining two full codebases. I can swap out a specific <div id="hero">.fetch handler.countries: ['US', 'CA'].7. Addressing Specific Constraints:
8. Refinement - "The Edge Personalization" aspect: Instead of just random A/B, I should add a rule: "If User is in UK, show Variant C (GBP pricing). Otherwise, run standard A/B."
9. Final Code Assembly (Mental Check):
10. Output Generation: (This matches the detailed response provided previously, ensuring all sections—Architecture, Fraud, Personalization, and Code—are covered.)
Self-Correction during drafting: Initially, I thought about fetching different origins. That's complex for a single code example. I will stick to HTML Rewriting. It allows one origin URL to serve multiple variants dynamically. It's cleaner for a tutorial.
Fraud Nuance: Simply blocking bots might skew data if the bot detection is aggressive. A better approach for experiments is to detect bots and force them into a specific bucket (usually Control) or exclude them from the data stream entirely. I will implement a "Shadow Ban" approach where bots see the page but don't influence the experiment logic.
(Self-Correction on Security): How to sign cookies? Workers don't have built-in strong encryption libraries easily accessible without Web Crypto API. I will use a simple HMAC signature using the Web Crypto API to sign the experiment bucket assignment so users can't manually edit variant=b to variant=winner.
Let's build the solution. This solution engineers a high-performance A/B testing framework directly at the edge using Cloudflare Workers. It moves experimentation logic out of the origin server or client-side JavaScript to ensure zero layout shift (CLS) and immediate personalization.
wrangler.toml)We need a KV namespace to store configuration and track rate limits.
name = "edge-experiment-engine"
main = "src/index.ts"
compatibility_date = "2024-04-05"
# Bindings for storing experiment configs and rate limit counters
[[kv_namespaces]]
binding = "EXPERIMENT_KV"
id = "your-kv-namespace-id"
src/index.ts)This code handles the security guardrails, bucketing logic, and HTML rewriting.
import { HTMLRewriter } from 'html-rewriter'; // Cloudflare native API
export interface Env {
EXPERIMENT_KV: KVNamespace;
}
// Define Experiment Variants
const VARIANTS = {
CONTROL: 'control',
VARIANT_A: 'variant_a', // e.g., "New Headline"
VARIANT_B: 'variant_b', // e.g., "New CTA Color"
};
// 1. Fraud Detection & Bot Guardrails
async function securityCheck(request: Request, env: Env): Promise<boolean> {
const ip = request.headers.get('cf-connecting-ip') || 'unknown';
const key = `ratelimit:${ip}`;
// Check 1: Native Cloudflare Bot Management
// @ts-ignore - cf object exists on Request in Worker runtime
const isBot = request.cf?.botManagement?.score > 30;
if (isBot) return false; // Drop request or serve control without tracking
// Check 2: Simple Rate Limiting (DDoS protection against data skew)
const count = await env.EXPERIMENT_KV.get(key);
if (count && parseInt(count) > 100) {
// If IP hits endpoint > 100 times in TTL, serve control but don't bucket.
return false;
}
// Increment counter
await env.EXPERIMENT_KV.put(key, (parseInt(count || '0') + 1).toString(), { expirationTtl: 60 });
return true; // User is valid
}
// 2. Personalization & Bucketing Logic
function assignVariant(request: Request): string {
// Personalization Rule: Mobile users always see Variant B
const ua = request.headers.get('user-agent') || '';
const isMobile = /Mobile|Android|iPhone/.test(ua);
// Edge Logic: Geo-targeting
// @ts-ignore
const country = request.cf?.country;
if (country === 'US' && isMobile) {
return VARIANTS.VARIANT_B;
}
// Standard Bucketing: Deterministic hash of UserID or Cookie
const userId = request.headers.get('x-user-id') || 'guest-' + Math.random();
// Simple hash function for bucketing (50% Control, 25% A, 25% B)
let hash = 0;
for (let i = 0; i < userId.length; i++) {
hash = ((hash << 5) - hash) + userId.charCodeAt(i);
hash |= 0;
}
const bucket = Math.abs(hash) % 100;
if (bucket < 50) return VARIANTS.CONTROL;
if (bucket < 75) return VARIANTS.VARIANT_A;
return VARIANTS.VARIANT_B;
}
// 3. HTML Rewriting (The "Injection")
// This allows us to modify the static HTML from origin without blocking the stream.
function rewriteHtml(response: Response, variant: string): Response {
const rewriter = new HTMLRewriter();
// Example: Change the Hero Title based on variant
if (variant === VARIANTS.VARIANT_A) {
rewriter.on('h1#hero-title', {
element(element) {
element.setInnerContent('Welcome to the Future of Engineering'); // Variant A Copy
}
});
}
// Example: Change CTA Color for Variant B
if (variant === VARIANTS.VARIANT_B) {
rewriter.on('button#cta-btn', {
element(element) {
element.setAttribute('style', 'background-color: #FF4500;'); // Change to Orange-Red
element.setAttribute('class', 'btn-experiment-b');
}
});
}
// Inject Tracking Script (Client-side analytics bridge)
rewriter.on('body', {
element(element) {
element.append(`
<script>
window.experimentConfig = { variant: '${variant}', date: '${new Date().toISOString()}' };
// Push to Data Layer here if needed
</script>
`, { html: true });
}
});
return rewriter.transform(response);
}
// Main Worker Entry Point
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
// Step 1: Run Fraud Checks
const isCleanTraffic = await securityCheck(request, env);
let assignedVariant = VARIANTS.CONTROL; // Default fallback
if (isCleanTraffic) {
// Step 2: Determine Variant
assignedVariant = assignVariant(request);
// Log assignment to analytics (Fire and forget)
ctx.waitUntil(
env.EXPERIMENT_KV.put(`stats:${assignedVariant}`, "1", { expirationTtl: 3600 })
);
}
// Step 3: Fetch Origin (Cache API enabled by default)
// We pass the variant in a header so the origin knows (optional)
const modifiedRequest = new Request(request, {
headers: { ...Object.fromEntries(request.headers), 'x-experiment-variant': assignedVariant }
});
const response = await fetch(modifiedRequest);
// Step 4: Rewrite Response (Only if HTML)
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('text/html')) {
return rewriteHtml(response, assignedVariant);
}
return response;
}
};
This is the "Sanity Check" layer. In experimentation, bot traffic creates noise. If a scraper hits your site 1,000 times, it shouldn't report that "Variant A" had 1,000 impressions.
request.cf.botManagement: Cloudflare automatically scores requests. We check this score. If it's a bot, we simply serve the Control variant but do not write to our stats KV. This keeps data clean.ctx.waitUntil: We use this to log stats asynchronously. The user gets the page immediately; the stats logging happens in the background.This uses a deterministic hashing algorithm.
Math.random()) breaks user experience because the user sees a different page every time they refresh.Hash("User123") will always result in the same number, ensuring User123 is always assigned to Variant A.We override the bucketing logic based on context available only at the Edge.
request.cf.country.User-Agent.This is the most critical engineering feature.
wrangler deploy.h1#hero-title.This architecture creates a sophisticated experimentation platform that is faster, more secure, and more reliable than client-side alternatives.