Vue SDK
A plugin, composables, a component and a directive for Vue 3. The server decides, so no targeting rules reach the browser.
Use this SDK in Vue 3.3 or newer and in Nuxt. It is built on the JavaScript SDK, so every client method there also works here. For server rendering, evaluate flags with the Node.js SDK. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
npm install @flagswift/vue- Requires
- Vue 3.3+
- Key
- Client key (fs_client_)
- Evaluates
- On the server, for one person
- Real-time updates
- Yes
- Works offline from
- localStorage cache
- Outcome analytics
- Yes
- Verified
- Unit tests
Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.
Installation#
npm install @flagswift/vue vueReactivity comes from one version ref that changes whenever the client does.
Initialization#
You need a client key (fs_client_…) from the API Keys page and the address of your FlagSwift server. Install the plugin once.
import { createApp } from "vue";
import { createFlagSwift } from "@flagswift/vue";
const flagswift = createFlagSwift({
apiKey: import.meta.env.VITE_FLAGSWIFT_KEY, // a client key: fs_client_...
baseUrl: "https://flags.example.com", // your FlagSwift server
user: { identifier: "user-42", account: "acme", attributes: { plan: "pro" } },
fallbacks: { "new-checkout": false },
});
createApp(App).use(flagswift).mount("#app");
// Outside components (router guards, stores):
// flagswift.client.isEnabled("new-checkout")Never a server key
fs_srv_…) in the browser.Connection options#
apiKey and baseUrl are required. The options are those of the JavaScript client, plus autoStart.
| Option | Type | Description |
|---|---|---|
| apiKey* | string | A client key. |
| baseUrl* | string | Your server address, starting with http:// or https://. |
| environment | string | Only for keys that cover every environment of a project. |
| user | FlagSwiftUser | Who is asking. Change it later with identify. |
| autoStart | boolean | Default: only in a browser, so server rendering opens no timers or requests. |
| refreshInterval | ms | How often to check for changes. Default 30000. 0 turns polling off. |
| streaming | boolean | Keep one real-time connection open so changes arrive at once. Default false. |
| fallbacks | { [flag]: value } | Served until flags load, and for flags the server does not know. |
| initialFlags | Record<string, ClientFlag> | Server-evaluated flags. Pass them to render flags on the server. |
| storage | adapter | false | Offline cache. localStorage by default; false turns it off. |
| autoExposures | boolean | Report an exposure the first time each outcome is read. Default false. |
| onError | function | Called when a refresh fails. Flags stay as they were. |
Check flags#
Composables are reactive: they update when flags refresh. Keys can be refs or getters, such as useFlag(() => props.flag).
<script setup lang="ts">
import { useFlag } from "@flagswift/vue";
const newCheckout = useFlag("new-checkout"); // ComputedRef<boolean>
</script>
<template>
<NewCheckout v-if="newCheckout" />
<OldCheckout v-else />
</template>Component and directive#
<FlagFeature> shows its content while a flag is on and a #fallback slot otherwise. v-flag hides an element with display: none while the flag is off.
<FlagFeature flag="beta-banner">
<Banner />
<template #fallback><p>Coming soon</p></template>
</FlagFeature>
<button v-flag="'export'">Export</button> <!-- hidden while OFF, still in the DOM -->v-flag only hides
v-if with useFlag when the element must not exist at all.Check variants and values#
useVariant gives the served variant's key and useFlagValue gives what it carries. useFlagMeta adds loading, error and known.
<script setup lang="ts">
import { useFlagMeta, useFlagValue, useVariant } from "@flagswift/vue";
const colour = useVariant("button-colour"); // ComputedRef<string | undefined>
const limit = useFlagValue<number>("upload-limit", 10); // the variant's value, or 10
const { loading, known } = useFlagMeta("upload-limit");
</script>
<template>
<p v-if="loading">Loading...</p>
<FlagFeature flag="checkout" variant="compact"><CompactCheckout :limit="limit" /></FlagFeature>
</template>useFlagValue keeps its identity when nothing changed, so watchers do not fire on every poll.
Change the person#
After a login, logout or tenant switch, call identify. Every flag is re-evaluated for the new person.
import { useFlagSwift } from "@flagswift/vue";
const { identify, refresh } = useFlagSwift();
await identify({ identifier: "user-43", account: "acme" });Offline, identify uses that person's cached flags if there are any, and otherwise keeps the previous flags rather than dropping to fallbacks.
If you already hold the new person's flags, for example evaluated on the server, pass them: identify(user, { flags }) shows them at once as bootstrap and then refreshes. The same user keeps its bootstrap or network flags rather than a stale cache, and getUser() returns the person being evaluated. From an identify without flags until the new person's flags arrive, automatic exposures are not reported and an explicit trackExposure is skipped, so an exposure is never credited to the wrong user.
Server rendering and Nuxt#
The plugin does nothing on the server unless you pass initialFlags, so renders are deterministic. For a first paint with no flicker, evaluate flags on the server with a server SDK, pass the result as initialFlags, and let the browser take over. In Nuxt, install the plugin from a Nuxt plugin.
import { createFlagSwift } from "@flagswift/vue";
export default defineNuxtPlugin((nuxt) => {
const cfg = useRuntimeConfig().public;
nuxt.vueApp.use(
createFlagSwift({
apiKey: cfg.flagswiftKey,
baseUrl: cfg.flagswiftUrl,
initialFlags: useState("flags", () => ({})).value,
}),
);
});Developer toolbar#
Render <DeveloperToolbar /> in development to inspect flags, force a flag on or off in this browser only, and try another user. Nothing is sent to FlagSwift. It is hidden in production builds.
<script setup lang="ts">
import { DeveloperToolbar } from "@flagswift/vue";
</script>
<template>
<DeveloperToolbar :enabled="import.meta.env.DEV" />
</template>See the developer toolbar guide for what it shows and its options.
Real-time updates#
By default the client polls. Set streaming: true and a flag change reaches the page within moments. The stream carries only a note that something changed, never flag data.
app.use(createFlagSwift({ apiKey, baseUrl, streaming: true }));If the stream drops, polling returns to its normal rate at once instead of waiting out the slower interval. If streaming is off on the server, or the connection cannot be kept, the client settles on polling. Flags keep working either way. client.getHealth().streaming reports off, connecting, connected or unavailable.
Offline and errors#
Once flags have loaded, the app keeps working with no internet and through a server outage. Checks read from memory, never touch the network and never throw.
| Situation | Description |
|---|---|
| A refresh fails | The last good flags stay. The error is set, onError is called, and polling backs off up to five minutes. The next success clears it. |
| First load, nothing cached | You get your fallbacks, then false, until the response arrives. Startup waits at most initTimeout (5 seconds). |
| Next page load, offline | The flags saved in localStorage apply at once. |
| Reading the state | useFlagMeta(...).error, or client.getState() for status, source and lastUpdated. |
Outcome analytics#
Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or turn autoExposures on, and only the person's identifier, the flag, the variant and the event name leave the browser.
const { client } = useFlagSwift();
client.trackExposure("checkout-redesign"); // this person was shown the flag's current outcome
await client.track("purchase", 49.9); // what they did, with an optional value
await client.flushAnalytics(); // send what is queued now (optional)At most 500 events wait in the queue. Once it is full, new ones are dropped silently (the ones already queued are kept) and counted in getHealth().analytics.dropped.
See Outcomes for how results are read in the console.
Reference#
Install with npm install @flagswift/vue (Vue 3.3 or newer). Reactivity comes from one version ref that changes whenever the client does.
| Export | Description |
|---|---|
| createFlagSwift(options | { client }) | Returns a plugin with .client and .context. Options are the JavaScript options plus autoStart (default: only in a browser, so server rendering opens no timers; pass initialFlags to render flags on the server). |
| useFlagSwift() | client, a computed state, identify(user, { flags? }) and refresh(). |
| useFlag(key, fallback?) | ComputedRef<boolean>. The key may be a ref or getter. |
| useVariant(key) | ComputedRef<string | undefined>. |
| useFlagValue(key, fallback?) | ComputedRef of the value. Keeps its identity when nothing changed, so watchers do not fire on every poll. |
| useFlagMeta(key) | enabled, variant, value, loading, error, known (whether the flag exists) and killSwitchActive. |
| useIsKillSwitchEnabled(key) | ComputedRef<boolean>. True when the server has disabled the flag with its kill switch. Local overrides are ignored on purpose, so a kill can never be masked. |
| <FlagFeature flag variant? invert?> | Renders the default slot when on (and the variant matches); #fallback or #else otherwise. |
| v-flag | Hides the element with display: none while off; it stays in the DOM. Accepts a flag key or { flag, variant, invert }. Use v-if with useFlag to remove it. |
| $flags | The client, on every component instance. |
| Teardown | The plugin destroys its client only when the app unmounts. Unmounting a single component never stops polling. |
| FLAGSWIFT_KEY, FlagSwift, FlagSwiftError | The injection key, the client class and the error class. |
Segments from your own code#
Put segment keys on the user and they count as extra segment membership: a flag that targets segment beta is turned on for a user who passes segments: ["beta"], even if the segment has no members or rules of its own in FlagSwift. Segments only decide on or off, so a kill switch or a disabled flag still wins, and variants are still chosen by the flag's allocation weights when it is on and its off variant when it is off. Changing the segments re-evaluates the flags.
const flagswift = createFlagSwift({
apiKey: "fs_client_...",
baseUrl: "https://flags.example.com",
user: { identifier: "u1", segments: ["beta", "staff"] },
});
// later: identify({ identifier: "u1", segments: ["beta"] })Trusted input