> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly-preview.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Vue SDK reference

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

> For the complete documentation index, see [llms.txt](/llms.txt). For the full documentation snapshot, see [llms-full.txt](/llms-full.txt).

## Overview

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

<Note title="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:
</Note>

| Resource | Location |
| - | - |
| SDK API documentation | [SDK API docs](https://launchdarkly.github.io/vue-client-sdk/) |
| Supported SDK Versions | [Vue SDK](../concepts/supported-versions#vue-sdk) |
| GitHub repository | [vue-client-sdk](https://github.com/launchdarkly/vue-client-sdk) |
| Sample application | [Vue](https://github.com/launchdarkly/vue-client-sdk/tree/main/example) |
| Published module | [npm](https://www.npmjs.com/package/launchdarkly-vue-client-sdk) |

## Get started

After you complete the [Get started](/home/getting-started) process, follow these instructions to start using the LaunchDarkly SDK in your Vue project:

* [Understand version compatibility](#understand-version-compatibility)
* [Install the SDK](#install-the-sdk)
* [Configure the SDK](#configure-the-sdk)
* [Initialize the client and context](#initialize-the-client-and-context)
* [Retrieve flag values for the context](#retrieve-flag-values-for-the-context)

### Understand version compatibility

The LaunchDarkly Vue SDK only works with Vue 3:

* Vue SDK 2.0 requires Vue 3.2 or newer
* Vue SDK 1.x requires Vue 3 or newer

For Vue 2 projects, you can use the [JavaScript SDK](/sdk/client-side/javascript) directly, or a community-developed package such as [vue-ld](https://github.com/dashhudson/vue-ld).

The Vue SDK is based on the JavaScript SDK. The Vue SDK builds on LaunchDarkly's JavaScript SDK to provide a better integration for use in Vue applications. 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](/sdk/client-side/javascript).

### Install the SDK

First, install the Vue SDK.

We recommend making the LaunchDarkly [observability plugins](/sdk/observability) available as well. These plugins collect and send observability data to LaunchDarkly, including [metrics autogenerated from observability events](/home/metrics/autogen/observability). This means you can review session replay, error monitoring, logs, and traces from within the LaunchDarkly UI. They require the Vue SDK version 2.4 or later.

Install the Vue SDK using either `npm` or `yarn`:

<CodeGroup>
  ```bash title="Installing with npm" theme={null}
      npm install --save launchdarkly-vue-client-sdk
      npm install @launchdarkly/observability # optional observability plugin
      npm install @launchdarkly/session-replay # optional session replay plugin
  ```

  ```bash title="Installing with yarn" theme={null}
      yarn add launchdarkly-vue-client-sdk
      yarn add @launchdarkly/observability # optional observability plugin
      yarn add @launchdarkly/session-replay # optional session replay plugin
  ```
</CodeGroup>

### Configure the SDK

The SDK provides a Vue plugin that you can add to your app. After you install the SDK, add the LaunchDarkly plugin to your Vue app. Typically you do this in `main.js`.

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.

<Warning title="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 in **Project settings**, on the **Environments** list. To learn more about key types, read [Keys](/sdk/concepts/client-side-server-side#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.
</Warning>

Here's how:

<CodeGroup>
  ```js title="main.js" theme={null}
      import { createApp } from 'vue'
      import App from './App.vue'
      import { LDPlugin } from 'launchdarkly-vue-client-sdk'

      // You'll need this context later, but you can ignore it for now.
      const clientSideID = 'example-client-side-id'

      const app = createApp(App)
      app.use(LDPlugin, { clientSideID })
      app.mount('#app')
  ```
</CodeGroup>

You can pass configuration options to the plugin when it loads, or to the `ldInit` function if you are using the `deferInitialization` option. To learn more, read [Initialize the client and context](#initialize-the-client-and-context), below.

The plugin exposes the LaunchDarkly client, as well as some convenience functions. The plugin uses the Vue provide/inject API to do this, which means these convenience functions will only work when run within Vue's setup hook or `<script setup>`. To learn more, read [Provide/Inject](https://vuejs.org/guide/components/provide-inject.html).

### Initialize the client and context

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

The SDK automatically initializes the LaunchDarkly client if you provide a `clientSideID` and do not use the `deferInitialization` option. The client begins attempting to connect to LaunchDarkly as soon as it is created. To determine when it is ready to use, we strongly recommend calling `waitForInitialization()`. This method takes a timeout, which we recommend setting to five seconds or fewer.

If you do not know the context at plugin load time and would like to defer initialization until you do, you can use the `deferInitialization` option. In this case, you will need to initialize the LaunchDarkly client manually with `ldInit`, which accepts the same `options` as the plugin.

We recommend making the LaunchDarkly [observability plugins](/sdk/observability) available as well, as shown in the configuration options below.

Here's how to initialize the client and verify it is ready to use:

<CodeGroup>
  ```js title="main.js" theme={null}
      import { createApp } from 'vue'
      import App from './App.vue'
      import { LDPlugin } from 'launchdarkly-vue-client-sdk'
      import Observability from '@launchdarkly/observability'
      import SessionReplay, { LDRecord } from '@launchdarkly/session-replay'

      const app = createApp(App)
      app.use(LDPlugin, {
        clientSideID: 'example-client-side-id',
        deferInitialization: true,
        options: {
          plugins: [
            new Observability(),
            new SessionReplay()
          ]
        }
      })
      app.mount('#app')
  ```

  ```html title="App.vue, Vue SDK v2.x" theme={null}
      <script setup>
      import { ldInit } from 'launchdarkly-vue-client-sdk'

      const [ldReady, ldClient] = ldInit({ context: { kind: 'user', key: 'example-context-key', name: 'Sandy' } })

      ldClient.waitForInitialization(5).catch((error) => {

        // Client encountered an error or timeout, but is ready to use.
        // variation() calls will return their fallback values.

        if (error?.name.toLowerCase().includes('timeout')) {
          console.log(`===== timeout error: ${error}`)
        } else {
          console.log(`===== other init error: ${error}`)
        }
      })

      </script>

      <template>
        <div v-if="ldReady">LaunchDarkly initialized.</div>
        <div v-else>LaunchDarkly initializing.</div>
      </template>
  ```
</CodeGroup>

To learn more about the available configuration options, read [`LDPluginOptions`](https://launchdarkly.github.io/vue-client-sdk/index.html#LDPluginOptions). To learn more about initialization, read [`ldInit`](https://launchdarkly.github.io/vue-client-sdk/index.html#ldInit) and [`waitForInitialization`](https://launchdarkly.github.io/vue-client-sdk/interfaces/LDClient.html#waitForInitialization).

### Determine when the client is ready

The client begins attempting to connect to LaunchDarkly as soon as it is created. 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 `ldReady`. `ldReady` is a ref, so to access its value outside of a template you need to use `ldReady.value`.

`ldReady` is returned by `ldInit`. Alternatively, you can retrieve `ldReady` independently using `useLDReady`.

Here's how:

<CodeGroup>
  ```html title="Vue" theme={null}
      <script setup lang="ts">
        import { useLDReady } from 'launchdarkly-vue-client-sdk'

        const ldReady = useLDReady()
      </script>

      <template>
        <div v-if="ldReady">... content that uses LaunchDarkly ...</div>
        <div v-else>LaunchDarkly client initializing...</div>
      </template>
  ```
</CodeGroup>

### Retrieve flag values for the context

Use `useLDFlag` to access a single flag value by key. It returns a readonly ref for the value of a flag. If you are using TypeScript, the ref's type can be inferred from the type of the fallback value provided to `useLDFlag`. To learn more about Vue refs, read [ref](https://vuejs.org/api/reactivity-core.html#ref) in the Vue.js documentation.

Here's how:

<CodeGroup>
  ```html title="Vue" theme={null}
      <script setup lang="ts">
        import { useLDFlag } from 'launchdarkly-vue-client-sdk'
        const featureFlagKey = 'my-boolean-flag'
        const myFlagValue = useLDFlag(featureFlagKey, false /* fallback flag value */)
      </script>

      <template>
        Feature flag "{{ featureFlagKey }}" has value "{{ myFlagValue }}".
      </template>
  ```
</CodeGroup>

The Vue SDK automatically subscribes to flag change events with `useLDFlag`, which opens a streaming connection. Then, your component re-renders automatically when flag changes occur.

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, use the `streaming: false` option when you load the plugin or when you call `ldInit`.

In other cases, streaming may be required. If you call `useLDFlag`, the SDK automatically opens a streaming connection. This is a benefit of `useLDFlag` as compared with getting flag values using the underlying JavaScript SDK, for example with `ldClient.variant()` or `ldClient.allFlags()`.

To learn more, read [`useLDFlag`](https://launchdarkly.github.io/vue-client-sdk/index.html#useLDFlag).

<Warning title="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](/home/account/edit-project).
</Warning>

### Access the underlying Java

Script SDK

You may also access the LaunchDarkly client with `useLDClient`, the [LDClient](https://launchdarkly.github.io/js-client-sdk/interfaces/LDClient.html) object from the underlying JavaScript SDK.

Here is an example:

<CodeGroup>
  ```js title="JavaScript" theme={null}
      <script setup>
      import { useLDClient } from 'launchdarkly-vue-client-sdk'

      const [ldReady] = ldInit({ clientSideID, context })
      const ldClient = useLDClient()
      </script>

      <template>
        <div v-if="ldReady">
          <p>All flags: {{ JSON.stringify(ldClient.allFlags()) }}</p>
        </div>
        <div v-else>LaunchDarkly client initializing...</div>
      </template>
  ```
</CodeGroup>

## Example app

An example app is included in [launchdarkly/vue-client-sdk](https://github.com/launchdarkly/vue-client-sdk/tree/main/example).

## 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"](https://support.launchdarkly.com/hc/en-us/articles/12998125691419-Error-LaunchDarklyFlagFetchError-network-error).
