Cloudflare
Read time: 5 minutes
Last edited: Oct 01, 2024
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.
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.
Create a Cloudflare Worker with the LaunchDarkly Cloudflare SDK
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:
-
Install Wrangler, the Workers CLI.
-
Authenticate Wrangler:
wrangler login
To learn more about the wrangler login
command, read login
.
-
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
.
-
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
.
-
Create a new Cloudflare Workers KV namespace:
wrangler kv:namespace create "LD_KV"
Wrangler responds with the namespace ID of the newly created namespace.
-
Add the
nodejs_compat
flag towrangler.toml
. This is required because the Cloudflare SDK usesnode:events
, which needs to be enabled:compatibility_flags = [ "nodejs_compat" ]To learn more, read Node.js compatibility.
-
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'swrangler.toml
file:kv_namespaces = [{ binding = "LD_KV", id="<LD_KV NAMESPACE ID>" }] -
(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 Configure the LaunchDarkly Cloudflare integration.
-
(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
.
-
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 Configure the LaunchDarkly Cloudflare integration.
Configure 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:
- Navigate to the Integrations page and search for "Cloudflare."
- Click Add integration. A "Create Cloudflare configuration" panel appears.
- (Optional) Enter a name for the integration.
- Choose an environment from the Environment menu.
- Enter your Cloudflare Account ID. You can find this on the Worker home in Cloudflare, in the right side navigation.
- Enter your KV Namespace ID.
- Enter your API token generated from Cloudflare.
- 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.
Use 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 ldClientconst 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-variablesldClient = 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 neededconst 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 Bootstrap using server-rendered content.