Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
When using LaunchDarkly developers need to first initialize the LaunchDarkly client like so ```ts import { createClient } from '@vercel/edge-config' import { LDClient, init } from '@launchdarkly/vercel-server-sdk' // create the edge config and launchdarkly clients const edgeConfigClient = createClient(process.env.EDGE_CONFIG) const ldClient = init(process.env.NEXT_PUBLIC_LD_CLIENT_SIDE_ID, edgeConfigClient) // wait for it to init of the launchdarkly client await ldClient.waitForInitialization() // use the launchdarkly client const flagValue = await ldClient.variation('my-flag', {}, true) ``` Intuitively a developer would do this ```ts export const runtime = 'edge' const edgeClient = createClient(process.env.EDGE_CONFIG) const ldClient = init(process.env.NEXT_PUBLIC_LD_CLIENT_SIDE_ID!, edgeClient) export default async function Home() { await ldClient.waitForInitialization() const flagValue = await ldClient.variation('my-flag', {}, true) ``` But this has a huge issue: It is not allowed to share promises across requests in Edge Runtime - more specifically in Cloudflare Workers which Edge Functions build on. When this page gets requested twice, then the first call to `ldClient.waitForInitialization()` creates a promise and the second call will await the promise created by the first request. This then leads to Cloudflare Workers throwing this error. But `waitForInitialization` catches that error and retries indefinitely until the function itself times out. To fix this, we could create a fresh client from within the home component like so ```ts const edgeConfigClient = createClient(process.env.EDGE_CONFIG) async function getLdClient(): Promise<LDClient> { const ldClient = init( process.env.NEXT_PUBLIC_LD_CLIENT_SIDE_ID, edgeConfigClient ) await ldClient.waitForInitialization() return ldClient } export default async function Home() { // get client from within the component so we get a fresh instance for every // request, otherwise LaunchDarkly might share promises across requests, which // can leads to timeouts in Edge Runtime const ldClient = await getLdClient() ``` But this has the issue that every call to `getLdClient` would create a fresh instance, even if the calls to `getLdClient` happen for the same request. To solve this, we can wrap `getLdClient` in `cache`, which caches the client for the duration of the server request and resets for each server request.
- Loading branch information