Browser SDKs

Vue SDK

Install and configure the Vue SDK, and evaluate configs and feature flags in Vue components

Introduction

The Vue SDK is intended to be used by Vue web applications running on modern web browsers. All modern web browsers on popular platforms should be supported.

The minimum supported version of Vue is 3.2.24.

Browser SDKs are tested on the latest versions of Chrome, Firefox, Safari, and Edge.

Telemetry collection within browser SDKs uses Web Workers to aggregate and send telemetry data. If the SDK runs on older browsers without Web Workers support, config evaluation will continue to work but no telemetry data will be collected for that session.

Installation

The SDK can be installed from NPM: https://www.npmjs.com/package/@configdirector/vue-sdk

npm install --save @configdirector/vue-sdk

Configure the plugin

Configure the Vue plugin with your client SDK key. This approach installs the ConfigDirectorPlugin and initializes the client asynchronously while your app is rendering:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);

app.use(ConfigDirectorPlugin, { sdkKey: "YOUR-CLIENT-SDK-KEY" });

app.mount("#app");

Alternatively, you can explicitly await on initializing the client before mounting the Vue app. The initialization timeout can be provided in the timeout option in milliseconds (defaults to 3,000ms). If initialization times out, the client will be returned and it will continue to attempt to initialize in the background:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin, initializeClient } from "@configdirector/vue-sdk";

async function bootstrap() {
  const app = createApp(App);

  const client = await initializeClient({ sdkKey: "YOUR_CLIENT_SDK_KEY" });
  app.use(ConfigDirectorPlugin, client);

  app.mount("#app");
}

bootstrap();

Additional configuration options

These configuration options can be passed in as plugin options to the ConfigDirectorPlugin or as additional options to initializeClient.

context

The context to be used during targeting rules evaluation:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);

app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR-CLIENT-SDK-KEY",
  context: {
    id: "12345",
    name: "Example User",
    traits: {
      region: "North America", // Any arbitrary traits which can be referenced in targeting rules
    },
  },
});

app.mount("#app");

logger

By default, the SDK logs to the console and it is set to log warnings and errors only. You can configure a logger by either creating a ConfigDirector console logger with a different log level, or by implementing the ConfigDirectorLogger interface to provide your own logger. The interface can be used to create an adapter to another logging library.

Configure the ConfigDirector console logger to a different level:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin, createConsoleLogger } from "@configdirector/vue-sdk";

const app = createApp(App);

app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR-CLIENT-SDK-KEY",
  logger: createConsoleLogger("debug"),
});

app.mount("#app");

Implement your own logger adapter:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin, ConfigDirectorLogger } from "@configdirector/vue-sdk";

const myLogger: ConfigDirectorLogger = {
  debug: function (message: string, ...args: any): void {
    // your specific logging library implementation here
  },
  info: function (message: string, ...args: any): void {
    // your specific logging library implementation here
  },
  warn: function (message: string, ...args: any): void {
    // your specific logging library implementation here
  },
  error: function (message: string, ...args: any): void {
    // your specific logging library implementation here
  },
};

const app = createApp(App);

app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR-CLIENT-SDK-KEY",
  logger: myLogger,
});

app.mount("#app");

appName and appVersion

These options allow you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);

app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR-CLIENT-SDK-KEY",
  appName: "YOUR-APP-NAME",
  appVersion: "1.0.2",
});

app.mount("#app");

timeout

The timeout, in milliseconds, to be used in initialization and when updating the context. This is how long the initializeClient function will wait for data from ConfigDirector services before resolving its Promise. If the timeout is reached, initializeClient will return but the client will still be in an unready status and returning default values. The client will continue to attempt to connect and retrieve config values in the background.

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin, initializeClient } from "@configdirector/vue-sdk";

async function bootstrap() {
  const app = createApp(App);

  const client = await initializeClient({
    sdkKey: "YOUR_CLIENT_SDK_KEY",
    timeout: 2_000, // 2,000 milliseconds timeout, defaults to 3,000
  });
  app.use(ConfigDirectorPlugin, client);

  app.mount("#app");
}

bootstrap();

mode

The connection mode, which can be streaming, polling or offline. It is recommended to use the default of streaming unless you have a specific need to use polling instead. Defaults to streaming.

Set mode to offline to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline client needs no sdkKey, opens no connection and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no lifecycle state changes. Every context receives the same value and targeting rules are not applied.

Give the values in the values option, with one value per config key. Your application decides where they come from, for example a module bundled with the test build:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);
app.use(ConfigDirectorPlugin, {
  mode: "offline",
  values: { "new-checkout": true, "max-items": 20 },
});
app.mount("#app");

The config type of each value follows from the value itself: a boolean, an integral number (integer), any other number (float), a string, or an object or array (json). A value read with an in-code default value of another type returns the in-code default value, as it does against ConfigDirector. The status turns ready right after the plugin is installed, and updating the context keeps the same values. values can be given only in offline mode, and pollingInterval, timeout and url have no effect in it. initializeClient takes the same options.

With mode: "offline" and no values, the client is ready at once and every config returns its in-code default value.

When the values cannot be loaded, because of a value such as null or because values is given in streaming or polling mode, the client never becomes ready: every config returns its in-code default value, the status stays loading, and the plugin reports a ConfigDirectorInitializationError as an unhandled promise rejection. initializeClient rejects with the same error.

If you come from LaunchDarkly, a map of values is what LaunchDarkly calls "flags from files", and offline with no values is its "offline mode".

values

The values to serve in offline mode, one value per config key. It can be given only in offline mode; see mode.

pollingInterval

The interval, in seconds, between requests for config updates when mode is polling. It has no effect in streaming mode. A value below the minimum of 30 seconds is raised to 30 seconds and a warning is logged. Defaults to 60 seconds. See Polling intervals.

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);
app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR_CLIENT_SDK_KEY",
  mode: "polling",
  pollingInterval: 120,
});
app.mount("#app");

url

The base URL used to connect to ConfigDirector services. This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services.

Values kept on the device

By default, the client keeps the last values it received from ConfigDirector in the browser's localStorage, and serves them on the next launch of the same context until live values arrive. An application opened without a network, after at least one successful connection, shows the values ConfigDirector last sent instead of the default values provided in code. Every evaluation served this way reports the reason cached, with isDefaultValue set to false.

The client is not ready while it serves values kept on the device: the status stays loading until the client's initialization completes with live values or its timeout, then default, and ready once live values arrive and replace them. The cachedValuesLoaded hook fires when the kept values are loaded, together with configsUpdated listing their keys, so watchers and hooks pick them up.

The values are kept for the context they were evaluated for, and served on the next launch only when the launch context has the same kind and id. A launch with another context serves the in-code default values until live values arrive, which then replace the kept values. A context without an id matches on the same site, as long as the site's data has not been cleared, because ConfigDirector derives its identifier from the instance ID the SDK stores; a context without an id keeps its percentage rollout bucket for as long as that instance ID lasts. Name, traits, app name and app version take no part in the match: live values correct them within a second when there is a network. Once the client is running, updating the context keeps serving the current values until the new context's values arrive, as it does with live values.

Turn it off, or supply your own store, with the caching option, which takes the same object the JavaScript SDK takes:

  • enabled
    • Whether to keep the last values received. With false, nothing is read or written, even when a provider is given.
    • Defaults to true
  • provider
    • A store of your own, for example an encrypted one, implementing CachingProvider: read() returns the stored entry or undefined, write(value) replaces it, remove() deletes it, and sizeLimit() returns the largest entry, in bytes, the store accepts. Each of read, write and remove may return a promise. One provider instance serves one client.
    • Defaults to the browser's localStorage, under a key derived from the client SDK key, with a size limit of 256 KB
main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);
app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR_CLIENT_SDK_KEY",
  caching: { enabled: false },
});
app.mount("#app");

The entry is one string whose format belongs to the SDK and may change between SDK versions; an entry a newer SDK cannot read is removed. Before every write the SDK measures the entry against sizeLimit(); above it, the entry is removed and a warning is logged once, so the device never serves values that no longer reflect the set. A provider that fails to read, write or remove is logged once and never stops the client: the worst outcome is the in-code default values. Keeping values on the device is ignored in offline mode.

The entry, and the localStorage key the SDK uses by default, carry a SHA-256 digest of the client SDK key, never the key itself. Browsers compute that digest only on pages served over https or from localhost, so on a plain http page on another host nothing is kept and a provider of your own is not called.

Retrieve config values

Retrieve a config value with the useConfigValue composable:

YourComponent.vue
<script setup lang="ts">
import { useConfigValue } from "@configdirector/vue-sdk";

const { value } = useConfigValue("my-config-key", false);
</script>

<template>
  <div>my-config-key is : {{ value }}</div>
</template>

You can also determine if the client is still initializing, so rather than transition from the default value to the evaluated value, you can show a loading state until the client is ready and config values are evaluated:

YourComponent.vue
<script setup lang="ts">
import { useConfigValue } from "@configdirector/vue-sdk";

const { value, loading } = useConfigValue("my-config", "default value");
</script>

<template>
  <div v-if="loading">Loading...</div>
  <div v-else>my-config is : {{ value }}</div>
</template>

Alternatively, you can also use the useClientStatus composable to retrieve just the status:

YourComponent.vue
<script setup lang="ts">
import { useClientStatus } from "@configdirector/vue-sdk";

const { loading } = useClientStatus();
</script>

<template>
  <div v-if="loading">Loading...</div>
  <div v-else><SomeComponentThatUsesConfigValues /></div>
</template>

Update the context

A context can be provided when initializing the plugin:

main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";

const app = createApp(App);

app.use(ConfigDirectorPlugin, {
  sdkKey: "YOUR-CLIENT-SDK-KEY",
  context: {
    id: "12345",
    name: "Example User",
    traits: {
      region: "North America", // Any arbitrary traits which can be referenced in targeting rules
    },
  },
});

app.mount("#app");

The context can also be updated via the useContext composable:

YourComponent.vue
<script setup lang="ts">
import { useConfigValue, useContext } from "@configdirector/vue-sdk";

const { updateContext } = useContext();
const { value } = useConfigValue("my-config-key", false);

const onUpdate = () => {
  updateContext({
    id: "654321",
    name: "Another User",
    traits: {
      region: "Australia",
    },
  });
};
</script>

<template>
  <div>my-config-key is : {{ value }}</div>
  <button type="button" @click="onUpdate">Update Context</button>
</template>

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with kind:

updateContext({
  id: "acme",
  kind: "tenant",
  name: "Acme Inc.",
  traits: {
    plan: "enterprise",
  },
});

Leaving kind out means user. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and configs are evaluated as if no context had been given. Context kinds are available from version 1.7.0 of the SDK.

In client SDKs (browser and mobile), updating the context re-establishes a new connection to ConfigDirector servers with the new context. While the new connection is in flight, config values will continue to evaluate to the currently cached values from the prior context.

The SDK keeps an instance ID in the browser's localStorage until the site's data is cleared, and ConfigDirector derives the identifier of a context without an id from it. A visitor who has not signed in keeps that identifier, and their percentage rollout bucket, from one visit to the next, and counts as one monthly active user however often they visit.

useClient composable

In the event that you need to have access to the underlying Javascript ConfigDirectorClient instance for more complex behaviors, you can access the instance via the useClient composable:

YourComponent.vue
<script setup lang="ts">
import { useClient } from "@configdirector/vue-sdk";

const { client } = useClient();

// Utilize the client for more involved logic
</script>

<template>
  <div>A component with more complex usage</div>
</template>
Proceed with caution when using the useClient composable. The useConfigValue and useContext composables manage listeners and cleanup automatically. However, if you make use of the useClient composable, you must manage cleaning up any listeners yourself.
Additionally, any calls to dispose, unwatch, or unwatchAll on the client instance can have unintended side effects and may result in subtle bugs.

evaluate

The client's evaluate(key, defaultValue) reads a config the way useConfigValue does and returns the evaluation behind the value: the value, whether it is the in-code default value, the reason, the valueId, and the variation. The JavaScript SDK describes it. Use it where the reason matters at the point of the read, such as when reporting an evaluation to another system. It reads once and does not update when the value changes, so keep rendering with useConfigValue. The SDK exports the ConfigEvaluation, EvaluationReason and Variation types. evaluate is available from version 1.10.0, and its variation from version 1.11.0.

CheckoutButton.vue
<script setup lang="ts">
import { useClient } from "@configdirector/vue-sdk";

const { client } = useClient();

const startCheckout = () => {
  const evaluation = client.evaluate("new-checkout", false);
  analytics.track("checkout-started", { newCheckout: evaluation.value, reason: evaluation.reason });
};
</script>

<template>
  <button @click="startCheckout">Check out</button>
</template>

track

The client's track(eventName, options) reports to ConfigDirector that something happened for the current context, such as a completed checkout, so ConfigDirector can show it on the Live feed and count it for each variation of a running experiment. options is optional and takes a value, a number the event measures, and details, an object describing the event. An event counts for an experiment only when the current context has an id. The JavaScript SDK describes the options and the limits. track is available from version 1.11.0.

PayButton.vue
<script setup lang="ts">
import { useClient } from "@configdirector/vue-sdk";

const { client } = useClient();

const pay = async () => {
  const order = await submitOrder();
  client.track("checkout-completed", { value: order.total, details: { plan: order.plan } });
};
</script>

<template>
  <button @click="pay">Pay</button>
</template>

Test your components

Use the SDK's testing entry point, @configdirector/vue-sdk/testing, to test components that read your configs and flags. It creates a test client: the SDK's real client connected to an in-memory server that your test controls. Only the connection to ConfigDirector is replaced. Everything else is the same code that runs in production, including the plugin and the composables, so your components behave exactly as they do against ConfigDirector, and no network connection is opened and no telemetry is sent.

Install the production plugin with the test client's client, the same way you would install it with a pre-initialized client:

Checkout.test.ts
import { nextTick } from "vue";
import { render, screen } from "@testing-library/vue";
import { ConfigDirectorPlugin } from "@configdirector/vue-sdk";
import { createTestClient } from "@configdirector/vue-sdk/testing";
import Checkout from "./Checkout.vue";

test("shows the new checkout when the flag is on", async () => {
  const testClient = createTestClient({ values: { "new-checkout": true } });

  render(Checkout, { global: { plugins: [[ConfigDirectorPlugin, testClient.client]] } });

  await screen.findByText("New checkout");

  testClient.setValue("new-checkout", false);
  await nextTick();
  screen.getByText("Classic checkout");
});

The plugin calls initialize on a client that is neither ready nor initializing, so the first assertion uses findBy… rather than getBy…; a test client whose client was initialized before app.use is ready on the first render, as with initializeClient. Await nextTick() after setValue, removeValue, and replaceValues, since they update the composables' refs synchronously and Vue renders on the next tick. The plugin's clientReady and contextUpdated handlers stay registered for the app's lifetime, as in production.

Test client controls

values, setValue, removeValue, and replaceValues take native values, and the config type follows from each value: a boolean, an integral number (integer), any other number (float), a string, or a plain object or array (json). holdInitialization, completeInitialization, and failInitialization drive initialize, so the loading and default statuses can be tested, and holdContextUpdate, completeContextUpdate, and failContextUpdate do the same for updateContext. contextUpdates records the context of every initialize and updateContext call, and trackedEvents the events the code under test tracked with track. The JavaScript SDK's testing section describes every control and what to expect from the client.