Skip to content
Snippets Groups Projects

Edge bucketing

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Derek Gathright
    Edited
    edge-bucketing.ts 1.74 KiB
    addEventListener("fetch", event => event.respondWith(handleRequest(event.request)));
    
    async function handleRequest(request) {
      // 1. Parse visitor ID from cookies
      const cookies = parseCookies(request.headers.get("cookie") || "");
      const visitorId = getMintedVisitorId(cookies);
    
      if (!visitorId) {
        return new Response("Missing visitor ID", { status: 400 });
      }
    
      // 2–4. Fetch flags from LaunchDarkly (via proxy or edge-compatible endpoint)
      const flags = await getFlagsForVisitor(visitorId);
    
      // 5. Add flags as headers
      const headers = new Headers(request.headers);
      for (const [flag, value] of Object.entries(flags)) {
        headers.set(`X-Minted-Experiment-${flag}`, String(value));
      }
    
      // 6. Forward request to origin (Minted)
      const upstreamUrl = new URL(request.url);
      upstreamUrl.hostname = "www.minted.com"; // or your actual origin
    
      const forwardedRequest = new Request(upstreamUrl.toString(), {
        method: request.method,
        headers,
        body: request.body,
      });
    
      return fetch(forwardedRequest);
    }
    
    function parseCookies(cookieHeader) {
      const cookies = {};
      cookieHeader.split(";").forEach(pair => {
        const [key, value] = pair.split("=").map(part => part.trim());
        if (key && value) cookies[key] = value;
      });
      return cookies;
    }
    
    function getMintedVisitorId(cookies) {
      // Return the first valid "Minted" visitor cookie
      for (const [key, value] of Object.entries(cookies)) {
        if (key.toLowerCase().includes("minted") && value) {
          return value;
        }
      }
      return null;
    }
    
    // This would ideally hit a LaunchDarkly-compatible edge API or gateway
    async function getFlagsForVisitor(visitorId) {
      const res = await fetch(`https://your-proxy.example.com/flags?user=${visitorId}`);
      if (!res.ok) return {};
      return res.json();
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment