• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
No results for ""
EXPAND ALL

GIVE DOCS FEEDBACK

Cloudflare

Read time: 5 minutes
Last edited: Feb 26, 2024
The Cloudflare integration is an Enterprise feature

The Cloudflare integration is available to customers on an Enterprise plan. To learn more, read about our pricing. To upgrade your plan, contact Sales.

Overview

This topic explains how to use LaunchDarkly's Cloudflare integration. This integration enables flag evaluation within Cloudflare Workers by writing the latest flag data from the configured environment directly to your Workers KV. To learn more about Cloudflare Workers KV, read How KV Works.

This integration requires LaunchDarkly's Cloudflare SDK

You must install and configure the Cloudflare SDK in your Cloudflare Worker to use this integration. To learn more, read Cloudflare SDK.

You can use the Cloudflare integration to bootstrap your application with the latest client-side feature flags. This eliminates the initial remote call to LaunchDarkly, providing zero-latency client-side feature flags with no flash of original content or shift in content layout. The Cloudflare integration also enables flag evaluations within a Worker.

Creating a Cloudflare Worker with the LaunchDarkly Cloudflare SDK

Cloudflare Workers KV size limits

Cloudflare Workers enforce KV size limits that might be smaller than your LaunchDarkly flag data in a given environment.

To learn more, read about KV limits.

To create a new Cloudflare Worker project with the LaunchDarkly Cloudflare SDK using the LaunchDarkly Cloudflare Worker template:

  1. Install Wrangler, the Workers CLI.

  2. Authenticate Wrangler:

    wrangler login

To learn more about the wrangler login command, read login.

  1. Create a new project using the LaunchDarkly Cloudflare Worker template. Replace my-project with the name of the project you wish to create:

    wrangler generate my-project https://github.com/launchdarkly/launchdarkly-cloudflare-worker-template

To learn more about the wrangler generate command, read generate.

  1. Add your Cloudflare account ID to your wrangler.toml file:

    account_id = "<YOUR_CLOUDFLARE_ACCOUNT_ID>"

If you do not know your Cloudflare account ID, use the command wrangler whoami.

  1. Create a new Cloudflare Workers KV namespace:

    wrangler kv:namespace create "LD_KV"

Wrangler responds with the namespace ID of the newly created namespace.

  1. Add the nodejs_compat flag to wrangler.toml. This is required because the Cloudflare SDK uses node:events, which needs to be enabled:

    compatibility_flags = [ "nodejs_compat" ]

    To learn more, read Node.js compatibility.

  2. Bind your Worker with the new KV namespace by adding the code Wrangler returned in step 5 to the kv_namespaces array in your Worker's wrangler.toml file:

    kv_namespaces = [
    { binding = "LD_KV", id="<LD_KV NAMESPACE ID>" }
    ]
  3. (Optional) If you intend to use wrangler dev for local development, you can also create a preview namespace:

    wrangler kv:namespace create "LD_KV" --preview

Wrangler responds with the updated IDs for your kv_namespaces array. Replace the existing array entry created above with the value returned by Wrangler.

kv_namespaces = [
{binding = "LD_KV", id="<LD_KV NAMESPACE ID>", preview_id = "<LD_KV NAMESPACE PREVIEW ID>"}
]

Each LaunchDarkly Cloudflare integration only populates one KV namespace. If you are using a preview KV namespace, it will require its own integration. To learn more, read Configuring the LaunchDarkly Cloudflare integration.

  1. (Optional) If you set up a preview namespace, you may run your worker locally:

    wrangler dev

To learn more about the wrangler dev command, read dev.

  1. Publish your Worker to Cloudflare:

    wrangler publish

To learn more about the wrangler publish command, read publish.

Your worker is running, but flag data will not be synced to your namespace until you set up the LaunchDarkly Cloudflare integration. To learn how, read Configuring the LaunchDarkly Cloudflare integration.

Configuring the LaunchDarkly Cloudflare integration

For a Cloudflare integration to work, it needs a Cloudflare API token. To create a Cloudflare API token read Creating API tokens. Your token needs to have Account - Workers KV Storage:Edit permissions.

You can create and manage Cloudflare integrations on the Integrations page. To create a new Cloudflare integration for your environment:

  1. Navigate to the Integrations page and search for Cloudflare.
  2. Click Add integration. A "Create Cloudflare configuration" panel appears.
  3. (Optional) Enter a name for the integration.
  4. Choose an environment from the Environment menu.
  5. Enter your Cloudflare Account ID. You can find this on the Worker home in Cloudflare, in the right side navigation.
  6. Enter your KV Namespace ID.
  7. Enter your API token generated from Cloudflare.
  8. Click Save configuration.

You can evaluate flags using the flag data that is set up to write to your Worker KV using the Cloudflare SDK.

Using the Cloudflare integration to bootstrap feature flags

You can use the LaunchDarkly Cloudflare integration with Workers Sites to serve HTML injected with feature flags for bootstrapping client-side SDKs. To learn more about Workers Sites, read Cloudflare's documentation.

To serve HTML injected with feature flags:

const { getAssetFromKV } = require('@cloudflare/kv-asset-handler')
const { init } = require('@launchdarkly/cloudflare-server-sdk')
let ldClient
const initLdClient = () => {
if (!ldClient) {
// LD_CLIENT_SIDE_ID and LD_KV are runtime variables that the Workers runtime provides to your code.
// For more information read https://developers.cloudflare.com/workers/platform/environment-variables
ldClient = init(LD_CLIENT_SIDE_ID, LD_KV)
return ldClient.waitForInitialization()
}
return Promise.resolve()
}
class FlagsStateInjector {
async element(element) {
// fetch all flag values for client-side SDKs as evaluated for an anonymous context
// use a more appropriate context key if needed
const context = { kind: 'user', key: 'context-key-123abc', anonymous: true }
const allFlags = await ldClient.allFlagsState(context)
element.append(`<script>window.ldFlags = ${JSON.stringify(allFlags)}</script>`, { html: true })
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
async function handleRequest(event) {
const [response] = await Promise.all([getAssetFromKV(event), initLdClient()])
const acceptHeader = event.request.headers.get('accept')
if (acceptHeader && acceptHeader.includes('text/html')) {
return new HTMLRewriter().on('head', new FlagsStateInjector()).transform(response)
}
return response
}

This uses HTMLRewriter to inject a script tag into the head of your document that saves your set of feature flags to window.ldFlags. To learn more about HTMLRewriter, read Cloudflare's documentation.

These flag values can then be used to bootstrap your client-side SDK. For example, if you are using the React Web SDK:

import React from 'react';
import { useFlags, withLDProvider } from 'launchdarkly-react-client-sdk';
const App = () => {
...
};
export default withLDProvider({
clientSideID: 'client-side-id-123abc',
options: {
bootstrap: window.ldFlags
}
})(App);

To learn more about bootstrapping client-side feature flags from the server, read Bootstrapping using server-rendered content.