> For the complete documentation index, see [llms.txt](https://docs.reflag.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.reflag.com/supported-languages/vue-sdk.md). Agents can also search and read this documentation through its [MCP server](https://docs.reflag.com/~gitbook/mcp).

# Vue SDK

Vue client side library for [Reflag.com](https://reflag.com)

Reflag supports flag toggling, tracking flag usage, requesting feedback on features and [multivariate flags](#multivariate-flags) that return strings, numbers or JSON objects.

The Reflag Vue SDK comes with the same built-in toolbar as the browser SDK which appears on `localhost` by default.

This page covers Vue SDK v2. For the legacy v1 SDK, see the [v1 docs](https://docs.reflag.com/legacy-sdks/v1/vue-sdk.md) and the [upgrade guide](https://docs.reflag.com/supported-languages/migrating-from-v1.md).

## Install <a href="#install" id="install"></a>

Install via npm:

```shell
npm i @reflag/vue-sdk
```

## Migrating from Bucket SDK <a href="#migrating-from-bucket-sdk" id="migrating-from-bucket-sdk"></a>

If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK:

* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`)
* `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`)
* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`)
* The `fallbackFeatures` property has been removed; pass a default to each `useFlag()` read instead
* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument
* The SDKs will not emit `evaluate` and `evaluate-config` events anymore
* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*`
* The `featuresUpdated` hook has been renamed to `flagsUpdated`
* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on

To ease in transition to Reflag SDK, the `featuresUpdated` hook has been preserved as an alias for `flagsUpdated`. The `getFeature` and `getFeatures` aliases have been removed; use `getFlag` and `getFlags` instead.

If you are running with strict Content Security Policies active on your website, you will need change them as follows:

* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com`

Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*`

## Get started <a href="#get-started" id="get-started"></a>

### 1. Add the `ReflagProvider` context provider <a href="#id-1-add-the-reflagprovider-context-provider" id="id-1-add-the-reflagprovider-context-provider"></a>

Add the `ReflagProvider` context provider to your application:

**Example:**

```vue
<script setup lang="ts">
import { ReflagProvider } from "@reflag/vue-sdk";

const publishableKey = "your-publishable-key";
</script>

<template>
  <ReflagProvider
    :publishable-key="publishableKey"
    :context="{
      user: { id: 'user_123', name: 'John Doe', email: 'john@acme.com' },
      company: { id: 'acme_inc', plan: 'pro' },
    }"
  >
    <!-- your app -->
  </ReflagProvider>
</template>
```

If using Nuxt, wrap `<ReflagProvider>` in `<ClientOnly>`. `<ReflagProvider>` only renders client-side currently.

### 2. Use `useFlag` to get flag status <a href="#id-2-use-useflag-to-get-flag-status" id="id-2-use-useflag-to-get-flag-status"></a>

```vue
<script setup lang="ts">
import { useFlag } from "@reflag/vue-sdk";

const isEnabled = useFlag("huddles"); // ShallowRef<boolean>
</script>

<template>
  <div v-if="isEnabled">
    <button>Start huddles!</button>
  </div>
</template>
```

`useFlag()` returns a ref. Vue unwraps it in templates; use `.value` in script. See [useFlag()](#useflag) for a full example

## Setting context <a href="#setting-context" id="setting-context"></a>

Reflag determines which flags are active for a given `user`, `company`, or `other` context. You can pass these to the `ReflagProvider` using the `context` prop.

### Using the `context` prop <a href="#using-the-context-prop" id="using-the-context-prop"></a>

```vue
<ReflagProvider
  :publishable-key="publishableKey"
  :context="{
    user: { id: 'user_123', name: 'John Doe', email: 'john@acme.com' },
    company: { id: 'acme_inc', plan: 'pro' },
    other: { source: 'web' },
  }"
>
  <!-- your app -->
</ReflagProvider>
```

### Legacy individual props (deprecated) <a href="#legacy-individual-props-deprecated" id="legacy-individual-props-deprecated"></a>

For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version:

```vue
<ReflagProvider
  :publishable-key="publishableKey"
  :user="{ id: 'user_123', name: 'John Doe', email: 'john@acme.com' }"
  :company="{ id: 'acme_inc', plan: 'pro' }"
  :other-context="{ source: 'web' }"
>
  <!-- your app -->
</ReflagProvider>
```

> \[!Important] The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way.

### Context requirements <a href="#context-requirements" id="context-requirements"></a>

If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. Attributes which are not properties of the `user` or `company` can be supplied using the `other` property.

Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. A number of special attributes exist:

* `name` -- display name for `user`/`company`,
* `email` -- the email of the user,
* `avatar` -- the URL for `user`/`company` avatar image.

To retrieve a flag's value, use the `useFlag(key: string)` hook (described in a section below).

Note that each `useFlag()` read automatically generates a `check` event.

## Multivariate flags <a href="#multivariate-flags" id="multivariate-flags"></a>

Multivariate flags are a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.

Instead of a Boolean, a multivariate flag returns one of several values, which can be strings, numbers or JSON objects. The values are managed from within Reflag, similar to the way access to flags is managed, and different users/companies can get different values.

### Get started with multivariate flags <a href="#get-started-with-multivariate-flags" id="get-started-with-multivariate-flags"></a>

Read a multivariate flag by passing a default. The default sets the type of the returned ref:

```ts
const settings = useFlag("huddle-settings", {
  maxTokens: 1000,
  model: "gpt-3.5",
});

// settings.value: { maxTokens: 10000, model: "gpt-3.5-beta1" }

useFlag("model", "quick"); // ShallowRef<string>
useFlag("limit", 10); // ShallowRef<number>
useFlag("anything", null); // ShallowRef<FlagValue>, any JSON value
```

`useFlag()` returns the default while flags load, or if the flag is missing or has a different JSON type, so make sure your default is a value your application can use. Pass `null` to accept any JSON value, then check its type before using it. The SDK doesn't check object fields or fill in missing fields from your default.

Without a default, `useFlag()` expects a Boolean and returns `false` if the flag is missing or isn't a Boolean.

Note that, similar to Boolean flags, each read of a multivariate flag automatically generates a `check` event.

Remote config from v1 isn't converted automatically. Move each remote config to a multivariate flag; see [Migrating from v1](#migrating-from-v1).

## Type safety <a href="#type-safety" id="type-safety"></a>

You can register your flags to get autocompletion for their keys and type checks for the defaults you pass:

```ts
import "@reflag/vue-sdk";

declare module "@reflag/vue-sdk" {
  interface Flags {
    huddles: boolean;
    "huddle-settings": { maxParticipants: number };
  }
}
```

The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `vue` format.

## `<ReflagProvider>` component <a href="#reflagprovider-component" id="reflagprovider-component"></a>

The `<ReflagProvider>` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props:

* `publishableKey` is used to connect the provider to an *environment* on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag,
* `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc.
* `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version.

  > \[!Note] If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against,
* `timeoutMs`: Timeout in milliseconds when fetching flags from the server,
* `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background,
* `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds),
* `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched.
* `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`),
* `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback,
* `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections.
* `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL,
* `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence,
* `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client,
* `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar,
* `feedback`: Optional configuration for feedback collection

### Loading states <a href="#loading-states" id="loading-states"></a>

ReflagProvider lets you define a template to be shown while ReflagProvider is initializing:

```vue
<template>
  <ReflagProvider
    :publishable-key="publishableKey"
    :user="user"
    :company="{ id: 'acme_inc', plan: 'pro' }"
  >
    <template #loading>Loading...</template>
    <StartHuddlesButton />
  </ReflagProvider>
</template>
```

If you want more control over loading screens, `useIsLoading()` returns a `Ref<boolean>` which you can use to customize the loading experience.

## `<ReflagBootstrappedProvider>` component <a href="#reflagbootstrappedprovider-component" id="reflagbootstrappedprovider-component"></a>

The `<ReflagBootstrappedProvider>` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility.

### Usage <a href="#usage" id="usage"></a>

```vue
<script setup lang="ts">
import {
  type BootstrappedFlags,
  ReflagBootstrappedProvider,
} from "@reflag/vue-sdk";

// Pre-fetched flags (typically from `getFlagsForBootstrap()` in your server/SSR layer)
const bootstrappedFlags: BootstrappedFlags = {
  protocolVersion: 2,
  context: {
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
  },
  flags: {
    huddles: { value: true, resolved: true, ruleResults: [], errors: [] },
    "huddle-settings": {
      value: { maxParticipants: 50, videoQuality: "hd" },
      variantKey: "enhanced",
      resolved: true,
      ruleResults: [],
      errors: [],
    },
  },
  flagStateVersion: 42,
};
</script>

<template>
  <ReflagBootstrappedProvider
    :publishable-key="publishableKey"
    :flags="bootstrappedFlags"
  >
    <StartHuddlesButton />
  </ReflagBootstrappedProvider>
</template>
```

### Getting bootstrapped flags <a href="#getting-bootstrapped-flags" id="getting-bootstrapped-flags"></a>

You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK. Pass the full object returned by `getFlagsForBootstrap()` directly to `<ReflagBootstrappedProvider>`. It contains:

* `protocolVersion`: the bootstrap format version
* `context`: the evaluation context used on the server
* `flags`: the evaluated raw flags
* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping

`getFlagsForBootstrap()` only includes flags that are marked as not secret (`secret: false`). Secret flags can still be read on the server. Because the browser can read the bootstrapped context, include only browser-safe attributes in it.

Use `@reflag/node-sdk` v2 to produce the bootstrap data. The Vue SDK v2 doesn't accept bootstrap data from Node SDK v1.

With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles.

Here's an example using the Node.js SDK:

```js
// server.js (Node.js/SSR)
import { ReflagClient } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: "your-secret-key", // Use secret key on server
});
await client.initialize();

// Fetch flags for specific context
const context = {
  user: { id: "user123", name: "John Doe", email: "john@acme.com" },
  company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
};

const bootstrappedFlags = client.getFlagsForBootstrap(context);

// Pass to your Vue app
```

### ReflagBootstrappedProvider Props <a href="#reflagbootstrappedprovider-props" id="reflagbootstrappedprovider-props"></a>

`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except:

* `flags`: The pre-fetched bootstrapped state object containing `protocolVersion`, `context`, evaluated `flags`, and an optional `flagStateVersion`
* All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`)

If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state.

{% hint style="info" %}
After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled.

Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled.
{% endhint %}

## `<ReflagClientProvider>` component <a href="#reflagclientprovider-component" id="reflagclientprovider-component"></a>

The `<ReflagClientProvider>` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application.

### ReflagClientProvider Usage <a href="#reflagclientprovider-usage" id="reflagclientprovider-usage"></a>

```vue
<script setup lang="ts">
import { ReflagClient } from "@reflag/browser-sdk";
import { ReflagClientProvider } from "@reflag/vue-sdk";

// Initialize the client yourself
const client = new ReflagClient({
  publishableKey: "your-publishable-key",
  user: { id: "user123", name: "John Doe" },
  company: { id: "company456", name: "Acme Inc" },
  // ... other configuration options
});

// Initialize the client. The provider shows the loading slot until it's ready.
void client.initialize();
</script>

<template>
  <ReflagClientProvider :client="client">
    <template #loading>Loading...</template>
    <Router />
  </ReflagClientProvider>
</template>
```

### ReflagClientProvider Props <a href="#reflagclientprovider-props" id="reflagclientprovider-props"></a>

The `ReflagClientProvider` accepts the following props:

* `client`: A pre-initialized `ReflagClient` instance

### Slots <a href="#slots" id="slots"></a>

* `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`)

> \[!Note] Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides.

## Hooks <a href="#hooks" id="hooks"></a>

### `useFlag()` <a href="#useflag" id="useflag"></a>

Returns the value of a given flag for the current context as a ref. The composable provides access to flags and their values.

`useFlag(key)` returns a `ShallowRef<boolean>`. With a default, `useFlag(key, defaultValue)` returns a ref whose type comes from the default; see [Multivariate flags](#multivariate-flags). The ref updates when flag values change. Use `useTrack()` to send a track event when the flag is used, `useRequestFeedback()` to open up a feedback dialog, and `useIsLoading()` to manage loading state.

Example:

```vue
<script setup lang="ts">
import {
  useFlag,
  useIsLoading,
  useRequestFeedback,
  useTrack,
} from "@reflag/vue-sdk";

const isLoading = useIsLoading();
const isEnabled = useFlag("huddles");
const settings = useFlag("huddle-settings", {
  question: "How do you like the Huddles feature?",
});
const track = useTrack();
const requestFeedback = useRequestFeedback();
</script>

<template>
  <div v-if="isLoading">Loading...</div>
  <div v-else-if="!isEnabled">Flag not available</div>
  <div v-else>
    <button @click="track('huddles')">Start huddles!</button>
    <button
      @click="
        (e) =>
          requestFeedback({
            flagKey: 'huddles',
            title: settings.question,
            position: {
              type: 'POPOVER',
              anchor: e.currentTarget as HTMLElement,
            },
          })
      "
    >
      Give feedback!
    </button>
  </div>
</template>
```

See the reference docs for details.

### `useOptInFlags()` <a href="#useoptinflags" id="useoptinflags"></a>

Use this composable to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. It returns the opt-in flags, their loading state and a `setOptIn` function.

```vue
<script setup lang="ts">
import { type OptInFlag, useIsLoading, useOptInFlags } from "@reflag/vue-sdk";

const isProviderLoading = useIsLoading();
const { flags: optInFlags, isLoading, setOptIn } = useOptInFlags();

async function toggleOptIn(flag: OptInFlag) {
  try {
    const response = await setOptIn(flag.key, {
      optedIn: !flag.userOptedIn,
    });
    if (!response?.ok) {
      console.error("Could not update opt-in");
    }
  } catch (error) {
    console.error("Could not update opt-in", error);
  }
}
</script>

<template>
  <p v-if="isProviderLoading || isLoading">Loading…</p>
  <template v-else>
    <button
      v-for="flag in optInFlags"
      type="button"
      :key="flag.key"
      @click="toggleOptIn(flag)"
    >
      {{ flag.userOptedIn ? "Cancel opt-in" : `Try ${flag.name}` }}
    </button>
  </template>
</template>
```

Each entry includes the flag's `key`, `name`, `description`, a Boolean `value` that says whether the flag is on, and whether the user (`userOptedIn`) or company (`companyOptedIn`) has opted in.

By default, `setOptIn` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`.

User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag.

`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet.

The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success.

`useOptInFlags()` returns `{ flags, isLoading, setOptIn }`, where `flags` and `isLoading` are computed refs. The separate `useSetOptIn()` composable still works but is deprecated. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails.

If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry.

With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state.

### `useTrack()` <a href="#usetrack" id="usetrack"></a>

`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event.

By default Reflag expects event names to align with the flag keys, so to track usage of a flag, call `track` with the flag key as the event name.

```vue
<script setup lang="ts">
import { useTrack } from "@reflag/vue-sdk";

const track = useTrack();
</script>

<template>
  <div>
    <button @click="track('Huddles Started', { huddlesType: 'voice' })">
      Start voice huddles!
    </button>
  </div>
</template>
```

### `useRequestFeedback()` <a href="#userequestfeedback" id="userequestfeedback"></a>

Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features.

See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code.

When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button.

```vue
<script setup lang="ts">
import { useRequestFeedback } from "@reflag/vue-sdk";

const requestFeedback = useRequestFeedback();
</script>

<template>
  <button
    @click="
      (e) =>
        requestFeedback({
          flagKey: 'huddles',
          title: 'How satisfied are you with file uploads?',
          position: {
            type: 'POPOVER',
            anchor: e.currentTarget as HTMLElement,
          },
        })
    "
  >
    Give feedback!
  </button>
</template>
```

See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/c9a90ea187026e2e22bdf5bd56df189b0fb12316/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options.

### `useSendFeedback()` <a href="#usesendfeedback" id="usesendfeedback"></a>

Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag.

```vue
<script setup lang="ts">
import { useSendFeedback } from "@reflag/vue-sdk";

const sendFeedback = useSendFeedback();

const handleSubmit = async (event: Event) => {
  const data = new FormData(event.currentTarget as HTMLFormElement);
  await sendFeedback({
    flagKey: "reflag-flag-key",
    score: parseInt(data.get("score") as string),
    comment: data.get("comment") as string,
  });
};
</script>

<template>
  <form @submit.prevent="handleSubmit">
    <!-- form content -->
  </form>
</template>
```

### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` <a href="#useupdateuser-useupdatecompany-and-useupdateothercontext" id="useupdateuser-useupdatecompany-and-useupdateothercontext"></a>

These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session.

```vue
<script setup lang="ts">
import {
  useUpdateUser,
  useUpdateCompany,
  useUpdateOtherContext,
} from "@reflag/vue-sdk";

const updateUser = useUpdateUser();
const updateCompany = useUpdateCompany();
const updateOtherContext = useUpdateOtherContext();

const handleUserUpdate = async () => {
  await updateUser({
    role: "admin",
    betaFeatures: "enabled",
  });
};

const handleCompanyUpdate = async () => {
  await updateCompany({
    plan: "enterprise",
    employees: 500,
  });
};

const handleContextUpdate = async () => {
  await updateOtherContext({
    currentWorkspace: "workspace-123",
    theme: "dark",
  });
};
</script>

<template>
  <div>
    <button @click="handleUserUpdate">Update User</button>
    <button @click="handleCompanyUpdate">Update Company</button>
    <button @click="handleContextUpdate">Update Context</button>
  </div>
</template>
```

Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables.

### `useClient()` <a href="#useclient" id="useclient"></a>

Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that is not directly accessible through the other composables.

```vue
<script setup>
import { useClient } from "@reflag/vue-sdk";
import { onMounted } from "vue";

const client = useClient();

console.log(client.getContext());
</script>

<template>
  <!-- your component content -->
</template>
```

### `useIsLoading()` <a href="#useisloading" id="useisloading"></a>

Returns a `Ref<boolean>` to indicate if Reflag has finished loading. Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized.

```vue
<script setup>
import { useIsLoading } from "@reflag/vue-sdk";
import { Spinner } from "./Spinner";

const isLoading = useIsLoading();
</script>

<template>
  <!-- your component content -->
</template>
```

### `useOnEvent()` <a href="#useonevent" id="useonevent"></a>

Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners.

Available events include:

* `flagsUpdated`: Triggered when flags are updated
* `track`: Triggered when tracking events are sent

```vue
<script setup lang="ts">
import { useOnEvent } from "@reflag/vue-sdk";

// Listen to flag updates
useOnEvent("flagsUpdated", () => {
  console.log("Flags have been updated");
});
</script>

<template>
  <!-- your component content -->
</template>
```

You can also provide a specific client instance if needed:

```vue
<script setup lang="ts">
import { ReflagClient } from "@reflag/browser-sdk";
import { useOnEvent } from "@reflag/vue-sdk";

const myReflagClient = new ReflagClient({
  publishableKey: "your-publishable-key",
});
void myReflagClient.initialize();

useOnEvent(
  "flagsUpdated",
  () => {
    console.log("flags updated");
  },
  myReflagClient,
);
</script>

<template>
  <!-- your component content -->
</template>
```

## Migrating from v1 <a href="#migrating-from-v1" id="migrating-from-v1"></a>

* `useFlag()` returns the flag's value as a ref: replace `const { isEnabled } = useFlag(key)` with `const isEnabled = useFlag(key)`. Use `.value` in script.
* Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically.
* Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`, and `useIsLoading()` instead of the flag's `isLoading`.
* Use the `setOptIn` function returned by `useOptInFlags()`. `useSetOptIn()` still works but is deprecated.
* Opt-in entries have a Boolean `value` instead of `isEnabled`.
* Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddles", true)`.
* If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time, and mark the flags the browser needs as not secret.
* If you generate type declarations, regenerate them with the v2 CLI.

See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps.

## Content Security Policy (CSP) <a href="#content-security-policy-csp" id="content-security-policy-csp"></a>

See [CSP](https://github.com/reflagcom/javascript/blob/c9a90ea187026e2e22bdf5bd56df189b0fb12316/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP

## License <a href="#license" id="license"></a>

MIT License

Copyright (c) 2025 Bucket ApS


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.reflag.com/supported-languages/vue-sdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
