Skip to main content

Vue.js SDK

Use Toggly's Vue.js SDK in Vue.js applications.

Requirements​

The package supports Vue ^3.2.45. Its declared minimum is Vue 3.2.45; the current tested host is Vue 3.5.42. Install Vue in the application as usual and let the package manager resolve the same Vue instance for the app and Toggly.

Installation​

Install the Vue.js feature flags package using NPM:

$ npm i -s @ops-ai/vue-feature-flags-toggly

Basic Usage (with Toggly.io)​

Setup Plugin​

Import the Toggly plugin in your main file:

import { toggly } from "@ops-ai/vue-feature-flags-toggly";

Install the toggly plugin while providing your App Key & Environment name from your Toggly application page. This will register the Feature component & $toggly service globally:

app.use(toggly, {
appKey: "your-app-key", // You can find this in app.toggly.io
environment: "your-environment-name", // You can find this in app.toggly.io
onError: (message, error) => {
// Report fetch/cache/refresh failures to your monitoring provider
console.warn('Toggly error:', message, error);
},
});

Using the Feature Component​

Now you can start using the Feature component anywhere in your application:

<Feature feature-key="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>

Feature Component Options​

You can also check multiple feature keys and make use of the requirement (all/any) and negate (bool) options (requirement is set to "all" by default).

Show when a flag is on​

<Feature feature-key="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>

Show if all of the listed features are on​

<Feature :feature-keys="['firstFeature', 'secondFeature']">
<p>ALL the provided feature keys are TRUE.</p>
</Feature>

Show if at least one of the listed features is on​

<Feature :feature-keys="['firstFeature', 'secondFeature']" requirement="any">
<p>AT LEAST ONE the provided feature keys is TRUE.</p>
</Feature>

Show if none of the listed features are on​

<Feature :feature-keys="['firstFeature', 'secondFeature']" requirement="all" :negate="true">
<p>NONE of the provided feature keys is TRUE.</p>
</Feature>

Feature vs FeatureGateBuilder​

NeedUse
Remove content from the DOM when off<Feature>
Keep content mounted; drive CSS, disabled state, or handlers<FeatureGateBuilder> or the useFeatureFlag / useFeatureGate composables

<Feature> adds no wrapper element — it renders the default slot directly when the gate is on. Prefer <FeatureGateBuilder> when the UI must stay visible but change appearance or behavior.

Use <FeatureGateBuilder> or composables when you need the resolved boolean for styling, taps, or behavior:

<FeatureGateBuilder feature-key="PremiumCheckout" v-slot="{ enabled }">
<button :class="{ active: enabled }" :disabled="!enabled">Checkout</button>
</FeatureGateBuilder>
import { useFeatureGate } from '@ops-ai/vue-feature-flags-toggly'

const { isEnabled } = useFeatureGate({ featureKeys: ['PremiumCheckout'] })

Both paths subscribe to remote refreshes and notifyLocalGatesChanged() for device-local post-filter gates.

When options depend on reactive props, pass a computed():

import { computed } from 'vue'
import { useFeatureGate } from '@ops-ai/vue-feature-flags-toggly'

const { isEnabled } = useFeatureGate(
computed(() => ({ featureKeys: ['PremiumCheckout'], requirement: props.mode })),
)

Directly Checking a Flag in Vue.js​

You can use $toggly to check if a feature is ON or OFF programmatically, by simply injecting it in any component:

export default {
inject: ['$toggly'],
...
}

Check if a feature is on​

await this.$toggly.isFeatureOn('firstFeature')

Check if a feature is off​

await this.$toggly.isFeatureOff('secondFeature')

Evaluate a feature gate (with requirement & negate support)​

await this.$toggly.evaluateFeatureGate(['firstFeature', 'secondFeature'], 'any', true)

Users and Rollouts​

Using this package with Toggly allows you to define custom feature rollouts.

Custom rollouts offers the ability to show features only to certain groups of users based on various custom rules which you can define in Toggly.

In case you want to support custom feature rollouts, remember to provide an unique identity string for each user to make sure they get the same feature values on future visits:

app.use(toggly, {
appKey: "<YOUR_APP_KEY>", // You can find this in app.toggly.io
environment: "<YOUR_APP_ENVIRONMENT>", // You can find this in app.toggly.io
identity: "<UNIQUE_USER_IDENTIFIER>", // Use this in case you want to support custom feature rollouts
// Optional init-time targeting (also accepted on setContext below)
groups: ['beta', 'enterprise'],
claims: { role: 'admin', plan: 'premium' },
});

For User Claims and group targeting after login, call setContext() on the $toggly service:

// Options API
await this.$toggly.setContext({
identity: user.id,
groups: user.groups,
claims: { role: user.role, plan: user.plan },
})
// Composition API
import { inject } from 'vue'

const $toggly = inject('$toggly')
await $toggly.setContext({
identity: user.id,
groups: user.groups,
claims: { role: user.role, plan: user.plan },
})

See Feature filters and Evaluated-signed.

success

When using user identifiers, evaluated features are cached per user for 30 minutes by default on a sliding window, so the user might not see the change right away as to not confuse the user. The session length is configurable and the session store can be cleared in App Settings

Live updates and signed definitions​

WebSocket live updates are on by default. Pass enableLiveUpdates: false to rely on HTTP polling only. Enable envelope verification with verifySignatures: true (optional allowedKeyIds, maxSignatureAgeSeconds):

app.use(toggly, {
appKey: 'your-app-key',
environment: 'your-environment-name',
enableLiveUpdates: true, // default
verifySignatures: true,
})

See WebSocket sync and Evaluated-signed.

Flag Defaults​

In case your application can't reach toggly, you can set feature defaults:

var featureFlagDefaults = {
firstFeature: true,
secondFeature: false,
}

app.use(toggly, {
appKey: "<YOUR_APP_KEY>", // You can find this in app.toggly.io
environment: "<YOUR_APP_ENVIRONMENT>", // You can find this in app.toggly.io
identity: "<UNIQUE_USER_IDENTIFIER>", // Use this in case you want to support custom feature rollouts
featureDefaults: featureFlagDefaults
});

Basic Usage (without Toggly.io)​

You can also use the Vue.js SDK without connecting to Toggly.io by providing feature defaults:

Setup Plugin with Defaults​

Import the Toggly plugin in your main file:

import { toggly } from "@ops-ai/vue-feature-flags-toggly";

Install the toggly plugin while providing your default feature flags. This will register the Feature component & $toggly service globally:

var featureDefaults = {
firstFeature: true,
secondFeature: false,
}

app.use(toggly, {
featureDefaults: featureDefaults,
});

Now you can use the Feature component the same way as with Toggly.io:

<Feature feature-key="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>

Error reporting and refresh behavior​

Pass onError when installing the plugin to observe fetch, cache, parse, and refresh failures:

app.use(toggly, {
appKey: 'your-app-key',
environment: 'your-environment-name',
onError: (message, error) => {
monitoring.captureException(error, {
tags: { source: 'toggly' },
extra: { message }
});
},
});

The $toggly service exposes lastError, which is updated before onError runs. After one successful load, refresh failures preserve the last-known-good flags instead of replacing rendered content with defaults or empty flags. <Feature> components subscribe to flag refreshes, so interval and WebSocket updates can re-render Vue UI automatically.

For the shared reliability contract, see Reliability and Error Handling.

Composition API Support​

If you're using Vue 3 Composition API, you can access the toggly service:

import { inject } from 'vue'

export default {
setup() {
const $toggly = inject('$toggly')

const checkFeature = async () => {
const isEnabled = await $toggly.isFeatureOn('firstFeature')
return isEnabled
}

return { checkFeature }
}
}

Best Practices​

  1. Install Plugin Once: Install the toggly plugin in your main.js/app.js file
  2. Use Feature Component: Prefer using the Feature component for declarative feature flag checks
  3. Inject Service: Use $toggly service for programmatic feature checks
  4. Provide User Context: Include identity for accurate targeting and rollouts
  5. Set Feature Defaults: Provide defaults for offline scenarios or when not using Toggly.io
  6. Composition API: Use inject to access $toggly in Composition API components

Extensibility with Hooks​

Toggly provides a powerful hooks system that allows you to extend SDK functionality by hooking into feature flag lifecycle events. This is perfect for integrating with analytics platforms like Microsoft Clarity, monitoring tools, or implementing custom behaviors.

What are Hooks?​

Hooks let you execute custom code at specific points in the feature flag evaluation lifecycle:

  • beforeEvaluation: Called before a feature flag is evaluated
  • afterEvaluation: Called after a feature flag is evaluated (with the result)
  • beforeIdentify: Called before user identity is set or cleared
  • afterIdentify: Called after user identity is set or cleared
  • afterRefresh: Called after feature definitions are refreshed from Toggly

Creating a Hook​

import { Hook } from '@ops-ai/toggly-hooks-types';

const myAnalyticsHook: Hook = {
getMetadata: () => ({
name: 'MyAnalyticsHook',
version: '1.0.0'
}),

afterEvaluation: async (flagKey, _data, result) => {
// Send to analytics
analytics.track('Feature Flag Evaluated', {
feature: flagKey,
enabled: result
});
}
};

Registering Hooks​

During plugin initialization:​

import { toggly } from '@ops-ai/vue-feature-flags-toggly';

app.use(toggly, {
appKey: 'your-app-key',
environment: 'your-environment-name',
hooks: [myAnalyticsHook]
});

Pass maxCacheKeys to cap identity-scoped localStorage entries (Client-side cache limits).

At runtime (Options API):​

<script>
export default {
inject: ['$toggly'],
mounted() {
this.$toggly.addHook(this.analyticsHook);
},
beforeUnmount() {
this.$toggly.removeHook(this.analyticsHook.getMetadata().name);
},
data() {
return {
analyticsHook: {
getMetadata: () => ({ name: 'Analytics', version: '1.0.0' }),
afterEvaluation: async () => {
// Your analytics logic
}
}
};
}
};
</script>

At runtime (Composition API):​

<script setup lang="ts">
import { inject } from 'vue';
import type { Toggly } from '@ops-ai/vue-feature-flags-toggly';
import { onMounted, onUnmounted } from 'vue';
import { Hook } from '@ops-ai/toggly-hooks-types';

const toggly = inject<Toggly>('$toggly');
if (!toggly) throw new Error('Install the Toggly plugin before using this component');

const analyticsHook: Hook = {
getMetadata: () => ({ name: 'Analytics', version: '1.0.0' }),
afterEvaluation: async (flagKey, _data, result) => {
// Your analytics logic
}
};

onMounted(() => {
toggly.addHook(analyticsHook);
});

onUnmounted(() => {
toggly.removeHook(analyticsHook.getMetadata().name);
});
</script>

Common Use Cases​

Microsoft Clarity Integration​

import type { Hook } from '@ops-ai/toggly-hooks-types';

const clarityHook: Hook = {
getMetadata: () => ({ name: 'Microsoft Clarity', version: '1.0.0' }),
afterEvaluation: async (flagKey, _data, result) => {
if (typeof clarity !== 'undefined') {
clarity('event', `FeatureFlag:${flagKey}`);
}
}
};

Vue Composable for Analytics​

import { inject } from 'vue';
import type { Toggly } from '@ops-ai/vue-feature-flags-toggly';
import { Hook } from '@ops-ai/toggly-hooks-types';
import { onMounted, onUnmounted } from 'vue';

export function useFeatureFlagAnalytics() {
const toggly = inject<Toggly>('$toggly');
if (!toggly) throw new Error('Install the Toggly plugin before using this component');

const analyticsHook: Hook = {
getMetadata: () => ({ name: 'Analytics', version: '1.0.0' }),
afterEvaluation: async (flagKey, _data, result) => {
// Track feature flag evaluation
trackEvent('feature_evaluated', {
feature: flagKey,
result: result
});
}
};

onMounted(() => {
toggly.addHook(analyticsHook);
});

onUnmounted(() => {
toggly.removeHook(analyticsHook.getMetadata().name);
});
}

Entity context​

Pass entity instances to <Feature> or $toggly.isFeatureOn — not to global user setContext(). See Entity & page context.

import { registerContext } from '@ops-ai/vue-feature-flags-toggly'

type Product = { sku: string; category: string; price: number }

registerContext<Product>('Product', (product) => ({
kind: 'Product',
key: product.sku,
attributes: { Category: product.category, Price: product.price },
}))

Feature component​

<Feature feature-key="NewProductBadge" :context="product" context-kind="Product">
<span class="badge">New</span>
</Feature>

Composable / service​

import { inject } from 'vue'
import type { TogglyService } from '@ops-ai/vue-feature-flags-toggly'

const toggly = inject<TogglyService>('$toggly')
if (!toggly) throw new Error('Install the Toggly plugin before using this component')
const enabled = await toggly.isFeatureOn('NewProductBadge', product, 'Product')

Mixed evaluated defs (boolean | EntityGate) are resolved locally; omitting context on a gated feature yields off.

See also​

Sample references​

Browse the Toggly Samples catalog for hands-on examples. Start with a sample’s README for setup instructions, then follow its source walkthrough to see how configuration, flag checks, and UI behavior fit together.

Try the Vue showcase and its README for a runnable Vue application with setup steps and a guided source walkthrough.

Next Steps​