Vue SDK reference

Recent major versions

Version 3 of the Vue SDK moves to the @launchdarkly/vue-client-sdk package, and replaces ldInit and useLDFlag with provider components and typed composables. To learn more about upgrading, read Vue SDK 2.x to 3.0 migration guide.

Version 2 of the Vue SDK introduces contexts. To learn more about upgrading, read Vue SDK 1.x to 2.0 migration guide.

This topic documents how to get started with the Vue SDK.

SDK quick links

LaunchDarkly’s SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:

ResourceLocation
SDK API documentationSDK API docs
Supported SDK VersionsVue SDK
GitHub repositoryvue
Sample applicationVue
Published modulenpm

Get started

After you complete the Get started process, follow these instructions to start using the LaunchDarkly SDK in your Vue project:

Understand version compatibility

The LaunchDarkly Vue SDK only works with Vue 3:

  • Vue SDK 3.0 requires Vue 3.3 or newer
  • Vue SDK 2.0 requires Vue 3.2 or newer
  • Vue SDK 1.x requires Vue 3 or newer

Version 3.0 raises the minimum Vue version because the reactive flag keys in its variation composables use Vue’s toValue function and MaybeRefOrGetter type, which Vue added in 3.3. To learn more, read Retrieve flag values for the context.

For Vue 2 projects, you can use the JavaScript SDK directly, or a community-developed package such as vue-ld.

The Vue SDK is based on the JavaScript SDK. As a result, much of the JavaScript SDK functionality is also available for the Vue SDK to use. For a complete client-side JavaScript SDK reference, read JavaScript SDK reference.

Version 3.0 of the Vue SDK builds on @launchdarkly/js-client-sdk, which is the JavaScript SDK at version 4.0 and higher. Version 2.x builds on launchdarkly-js-client-sdk, which is the JavaScript SDK at version 3.x. The changes described in the JavaScript SDK 3.x to 4.0 migration guide also apply to the Vue SDK.

Install the SDK

First, install the Vue SDK. Version 3.0 renames the package from launchdarkly-vue-client-sdk to @launchdarkly/vue-client-sdk.

We recommend making the LaunchDarkly observability plugins available as well. These plugins collect and send observability data to LaunchDarkly, including metrics autogenerated from observability events. This means you can review session replay, error monitoring, logs, and traces from within the LaunchDarkly UI. In version 3.0, you pass them to the SDK in the ldOptions property. In the 2.x releases, they require version 2.4 or later.

Install the Vue SDK using either npm or yarn:

npm install --save @launchdarkly/vue-client-sdk
npm install @launchdarkly/observability # optional observability plugin
npm install @launchdarkly/session-replay # optional session replay plugin

Configure the SDK

In version 3.0, the SDK provides two ways to create the LaunchDarkly client and make it available to your components:

  • LDVuePlugin is a Vue plugin that you install with app.use(). It provides the client to your entire app. Typically you do this in main.js.
  • createLDProvider returns a component that you render in your template. Unlike the plugin, the provider component supports initializing and failed slots, which let you gate rendering on the initialization state without calling a composable.

Version 2.x offered only the plugin, which was named LDPlugin.

To configure the Vue SDK, you need your LaunchDarkly environment’s client-side ID and the context for which you want to evaluate flags. This authorizes your application to connect to a particular environment within LaunchDarkly. Version 3.0 requires both values when you install the plugin or create a provider.

Vue SDK credentials

The Vue SDK requires a client-side ID. Client-side IDs are specific to each project and environment. They are not secret, and you can include them in client-side code. Do not embed a server-side SDK key in a client-side application. You can find client-side IDs and project keys on the SDK keys page under Settings. To learn more about key types, read Keys.

If you connect the Vue SDK to the ldcli dev-server for local testing, use your project key instead of a client-side ID. Set all service endpoints to http://localhost:8765. If you use a client-side ID, the SDK connects to LaunchDarkly instead of the dev-server, which can result in CORS errors.

Here’s how to register the plugin:

import { createApp } from 'vue'
import App from './App.vue'
import { LDVuePlugin } from '@launchdarkly/vue-client-sdk'
const app = createApp(App)
app.use(LDVuePlugin, {
clientSideID: 'example-client-side-id',
context: { kind: 'user', key: 'example-context-key', name: 'Sandy' }
})
app.mount('#app')

Pass configuration options for the underlying JavaScript SDK in the ldOptions property. In version 2.x, these options were in a top-level options property. To learn more, read LDVuePluginOptions and LDOptions.

The plugin and the provider expose the LaunchDarkly client, as well as some convenience composables. They use the Vue provide/inject API to do this, which means these composables only work when you run them within Vue’s setup hook or <script setup>. To learn more, read Provide/Inject.

Initialize the client and context

After you configure the Vue SDK, initialize the LaunchDarkly client and the context. The context provides information about the end user who is encountering feature flags in your application.

Both the plugin and the provider create the client and begin connecting to LaunchDarkly immediately, unless you pass deferInitialization: true. Version 3.0 requires a context, and does not create an anonymous context on your behalf. If you do not know the context yet, pass an explicit anonymous context such as { kind: 'user', anonymous: true }, then call identify() on the client when you learn who the end user is.

To determine when the client is ready to use, gate rendering with the provider’s initializing and failed slots, or call useInitializationStatus in a component. To learn more, read Determine when the client is ready, below.

We recommend making the LaunchDarkly observability plugins available as well, as shown in the configuration options below.

Here’s how to initialize the client and gate rendering on its initialization state:

import { createLDProvider } from '@launchdarkly/vue-client-sdk'
import Observability from '@launchdarkly/observability'
import SessionReplay from '@launchdarkly/session-replay'
// Create the provider once, outside of any component.
export const LDProvider = createLDProvider(
'example-client-side-id',
{ kind: 'user', key: 'example-context-key', name: 'Sandy' },
{
ldOptions: {
plugins: [
new Observability(),
new SessionReplay()
]
}
}
)

To control when the client connects to LaunchDarkly, set deferInitialization: true and start the client yourself. Version 3.0 removes the ldInit function that version 2.x used for this. The client already exists as soon as the plugin or provider runs, so retrieve it with useLDClient and call start() on it.

Here’s how:

Deferred initialization, Vue SDK v3.0
<script setup>
import { useLDClient } from '@launchdarkly/vue-client-sdk'
// The plugin or provider was configured with `deferInitialization: true`.
const ldClient = useLDClient()
ldClient.start({ timeout: 5 }).then((result) => {
if (result.status !== 'complete') {
console.log(`===== LaunchDarkly did not finish initializing: ${result.status}`)
}
})
</script>

To set an initialization timeout or provide bootstrap data, use the startOptions and bootstrap options. We recommend a timeout of five seconds or fewer. If you set both bootstrap and startOptions.bootstrap, the top-level bootstrap value takes precedence.

Here is an example:

Timeout and bootstrap, Vue SDK v3.0
app.use(LDVuePlugin, {
clientSideID: 'example-client-side-id',
context: { kind: 'user', key: 'example-context-key' },
startOptions: { timeout: 5 },
bootstrap: serverSideFlagValues
})

For advanced patterns such as testing or multi-step bootstrapping, createClient and createLDProviderWithClient let you create and own the client instance separately from the provider component that renders it. If you use createLDProviderWithClient, you are responsible for calling client.start().

To learn more about the available configuration options, read LDVuePluginOptions. To learn more about initialization, read createLDProvider and LDVuePlugin.

Determine when the client is ready

The client begins attempting to connect to LaunchDarkly as soon as it creates the connection. Then, you must check that it is ready to use. If you do not confirm this, your application may wait indefinitely if LaunchDarkly is unavailable.

To find out when the client has finished initializing, use useInitializationStatus. It returns a computed ref to an InitializationStatus object, so to access its value outside of a template you need to use status.value. The object’s status field covers the full initialization lifecycle with a value of initializing, complete, timeout, or failed. When the status is failed, the object also includes an error field. When the status is timeout, the client did not finish initializing within the configured limit, but you can still evaluate flags and receive fallback values. This matches version 2.x behavior, where useLDReady became true after a timeout.

Version 3.0 removes useLDReady, which returned a boolean rather than the full lifecycle.

Here’s how:

<script setup lang="ts">
import { useInitializationStatus } from '@launchdarkly/vue-client-sdk'
const status = useInitializationStatus()
</script>
<template>
<div v-if="status.status === 'complete' || status.status === 'timeout'">... content that uses LaunchDarkly ...</div>
<div v-else-if="status.status === 'failed'">LaunchDarkly client failed to initialize: {{ status.error.message }}</div>
<div v-else>LaunchDarkly client initializing...</div>
</template>

To reproduce the boolean that version 2.x useLDReady returned, derive it with computed:

Vue SDK v3.0
import { computed } from 'vue'
import { useInitializationStatus } from '@launchdarkly/vue-client-sdk'
const status = useInitializationStatus()
const ldReady = computed(() => status.value.status === 'complete' || status.value.status === 'timeout')

For advanced cases that bypass the composables, the client that useLDClient returns still exposes the full base LDClient API, including waitForInitialization() and the ready event. To learn more, read Access the underlying JavaScript SDK, below.

To learn more, read useInitializationStatus.

Retrieve flag values for the context

Version 3.0 provides a typed composable for each flag type:

  • useBoolVariation for boolean flags
  • useStringVariation for string flags
  • useNumberVariation for numeric flags
  • useJsonVariation for JSON flags

Each composable accepts a flag key and a default value, and returns a readonly ref for the value of the flag. The composable’s name determines the return type, so if you are using TypeScript, you no longer need a type parameter. The default value is required. To learn more about Vue refs, read ref in the Vue.js documentation.

Version 3.0 removes the generic useLDFlag composable that version 2.x used for every flag type.

Here’s how:

<script setup lang="ts">
import { useBoolVariation, useStringVariation } from '@launchdarkly/vue-client-sdk'
const featureFlagKey = 'my-boolean-flag'
const myFlagValue = useBoolVariation(featureFlagKey, false /* default flag value */)
const theme = useStringVariation('ui-theme', 'default')
</script>
<template>
Feature flag "{{ featureFlagKey }}" has value "{{ myFlagValue }}".
</template>

In version 3.0, each variation composable also accepts a reactive flag key, either a Ref<string> or a getter function. When the key changes, the composable re-evaluates, so a component can change which flag it evaluates at runtime without unmounting. Version 2.x had no equivalent.

Here is an example:

Reactive flag key, Vue SDK v3.0
import { ref } from 'vue'
import { useBoolVariation } from '@launchdarkly/vue-client-sdk'
const flagKey = ref('example-flag-key')
const enabled = useBoolVariation(flagKey, false)
flagKey.value = 'another-flag-key' // `enabled` re-evaluates automatically

To retrieve the evaluation reason and variation index along with the value, use the useBoolVariationDetail, useStringVariationDetail, useNumberVariationDetail, and useJsonVariationDetail composables. Each one returns a readonly ref for an evaluation detail object. Before the client is ready, the detail contains the default value and a CLIENT_NOT_READY error reason. The SDK populates the reason field only when you enable the withReasons option in ldOptions. Version 2.x had no equivalent.

Here is an example:

Evaluation detail, Vue SDK v3.0
import { useBoolVariationDetail } from '@launchdarkly/vue-client-sdk'
const detail = useBoolVariationDetail('example-flag-key', false)
// detail.value.value -> boolean
// detail.value.reason -> LDEvaluationReason
// detail.value.variationIndex -> number | null

To learn more, read Flag variation evaluation and Evaluation reasons.

Making feature flags available to this SDK

You must make feature flags available to client-side SDKs before the SDK can evaluate those flags. If an SDK tries to evaluate a feature flag that is not available, the end user will receive the fallback value for that flag.

To make a flag available to this SDK, check the SDKs using Client-side ID checkbox during flag creation, or toggle on the option in the flag’s right sidebar. To make all of a project’s flags available to this SDK by default, check the SDKs using Client-side ID checkbox on your project’s Flag settings page.

Subscribe to flag changes

The Vue SDK automatically subscribes to flag change events when you use a variation composable or a variation detail composable, which opens a streaming connection. Then, your component re-renders automatically when flag changes occur. This is a benefit of the variation composables as compared with getting flag values from the underlying JavaScript SDK, for example with ldClient.boolVariation() or ldClient.allFlags().

In some cases, streaming may not be necessary. For example, if you reload your entire application on each update, you will get all the flag values again when the client is re-initialized. If you do not want flag updates streamed to your application, set streaming: false in ldOptions. In version 2.x, streaming was a top-level plugin option.

In other cases, streaming may be required. Subscribing to streaming is the only way to receive real-time updates. If you determine that streaming is necessary for your application, we recommend enabling it explicitly.

Here’s how to configure streaming explicitly:

Vue SDK v3.0
app.use(LDVuePlugin, {
clientSideID: 'example-client-side-id',
context: { kind: 'user', key: 'example-context-key' },
ldOptions: {
streaming: true // or `false` to disable
}
})

To learn more, read streaming and Subscribing to flag changes.

Access the underlying JavaScript SDK

You may also access the LaunchDarkly client with useLDClient. In version 3.0, this returns an LDVueClient object, which is a superset of the LDClient object from the underlying JavaScript SDK. In version 2.x, useLDClient returned the base LDClient object.

Every LDClient method, such as identify, close, and on, remains available. In addition, LDVueClient provides these methods:

  • getInitializationState() returns the client’s initialization state.
  • getInitializationError() returns the error that caused initialization to fail, if any.
  • isReady() returns whether the client can evaluate flags.
  • onContextChange() subscribes to the context changes that identify() triggers.
  • onInitializationStatusChange() subscribes to initialization status changes.

Both subscription methods return a function that unsubscribes the callback.

Here is an example:

<script setup lang="ts">
import { useInitializationStatus, useLDClient } from '@launchdarkly/vue-client-sdk'
import type { LDVueClient } from '@launchdarkly/vue-client-sdk'
const status = useInitializationStatus()
const ldClient: LDVueClient = useLDClient()
</script>
<template>
<div v-if="status.status === 'complete' || status.status === 'timeout'">
<p>All flags: {{ JSON.stringify(ldClient.allFlags()) }}</p>
</div>
<div v-else>LaunchDarkly client initializing...</div>
</template>

Multi-environment support

Version 3.0 supports connecting to more than one LaunchDarkly environment from the same application. Each environment gets its own injection key, provider, and client. Create a key with createLDVueInstanceKey, pass it to the injectionKey option on each plugin or provider, and pass the same key to any composable that should read from that environment. Version 2.x had no equivalent.

Here is an example:

import { createLDProvider, createLDVueInstanceKey } from '@launchdarkly/vue-client-sdk'
const context = { kind: 'user', key: 'example-context-key' }
export const prodKey = createLDVueInstanceKey()
export const stagingKey = createLDVueInstanceKey()
export const ProdLDProvider = createLDProvider('prod-client-side-id', context, {
injectionKey: prodKey
})
export const StagingLDProvider = createLDProvider('staging-client-side-id', context, {
injectionKey: stagingKey
})

If you nest providers that use the same injection key, the inner provider shadows the outer one for its descendants. To avoid this, create a separate injection key for each environment.

Each client’s lifecycle, including identify(), is independent. Call identify() on each client when the context changes.

Shut down the client

Shut down the client when your application terminates. LDVueClient inherits the close() method from the base LDClient, so you can call it on the client that useLDClient returns. To learn more, read Shutting down.

Example app

An example app is included in launchdarkly/js-core.

Troubleshooting

If your application logs show the error LaunchDarklyFlagFetchError: network error, it may indicate a problem with network connectivity between your SDK and LaunchDarkly.

For steps to resolve this issue, read the LaunchDarkly Knowledge Base article Error “LaunchDarklyFlagFetchError: network error”.

Supported features

This SDK supports the following features: