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

EDIT ON GITHUB

Cloudflare

Read time: 2 minutes
Last edited: Nov 09, 2021
This feature is for Early Access Program customers only

The Cloudflare integration is only available to members of LaunchDarkly's Early Access Program (EAP). If you want access to this feature, join the EAP.

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 Edge SDK

You must install and configure the Cloudflare Edge SDK in your Cloudflare Worker to use this integration. To learn more, read Cloudflare Edge 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 Edge SDK

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

  1. Install Wrangler, the Workers CLI.

  2. Authenticate Wrangler:

1wrangler 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:
1wrangler 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:
1account_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:
1wrangler kv:namespace create "MY_KV"

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

  1. 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:
1kv_namespaces = [
2 { binding = "MY_KV", id = "<NAMESPACE_ID>" }
3]
  1. (Optional) If you intend to use wrangler dev for local development, you can also create a preview namespace:
1wrangler kv:namespace create "MY_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.

1kv_namespaces = [
2 { binding = "MY_KV", preview_id= "<PREVIEW_NAMESPACE_ID>", id = "<NAMESPACE_ID>" }
3]

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:
1wrangler dev

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

  1. Publish your Worker to Cloudflare:
1wrangler 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.
  3. (Optional) Enter a name for the integration.
  4. Choose an environment from the Environment dropdown menu.
  5. Enter your Cloudflare account ID.
  6. Enter your KV Namespace ID.
  7. Enter your API token generated from Cloudflare.
  8. Click Save configuration.

The LaunchDarky Cloudflare integration screen.
The LaunchDarky Cloudflare integration screen.

You can evaluate flags using the flag data that is set up to write to your Worker KV using the Cloudflare Edge 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:

1const { getAssetFromKV } = require('@cloudflare/kv-asset-handler');
2const { init } = require('launchdarkly-cloudflare-edge-sdk');
3
4let ldClient;
5
6const initLdClient = () => {
7 if (ldClient) {
8 return Promise.resolve();
9 }
10
11 ldClient = init(MY_KV, 'YOUR_CLIENT_SIDE_ID');
12 return ldClient.waitForInitialization();
13};
14
15class FlagsStateInjector {
16 async element(element) {
17 // fetch all flag values for client-side SDKs as evaluated for an anonymous user
18 // use a more appropriate user key if needed
19 const user = { key: 'anonymous' };
20 const allFlags = await ldClient.allFlagsState(user, { clientSideOnly: true });
21 element.append(`<script>window.ldFlags = ${JSON.stringify(allFlags)}</script>`, { html: true });
22 }
23}
24
25addEventListener('fetch', event => {
26 event.respondWith(handleRequest(event));
27});
28
29async function handleRequest(event) {
30 const [response] = await Promise.all([getAssetFromKV(event), initLdClient()]);
31 const acceptHeader = event.request.headers.get('accept');
32
33 if(acceptHeader && acceptHeader.includes('text/html')) {
34 return new HTMLRewriter().on('head', new FlagsStateInjector()).transform(response);
35 }
36
37 return response;
38}

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 client SDK:

1import React from 'react';
2import { useFlags, withLDProvider } from 'launchdarkly-react-client-sdk';
3
4const App = () => {
5 ...
6};
7
8export default withLDProvider({
9 clientSideID: 'YOUR_CLIENT_SIDE_ID',
10 options: {
11 bootstrap: window.ldFlags
12 }
13})(App);

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