Skip to main content

Flagmint Vue.js SDK

A lightweight and powerful feature flag SDK for Vue 2 and Vue 3 applications with real-time updates via WebSocket.

Features

Vue 2 & 3 Support

Works seamlessly with both Vue 2 and Vue 3

Real-time Updates

WebSocket and HTTP long-polling support

Segment Targeting

Advanced targeting rules and rollout strategies

Offline Ready

Built-in caching and preview mode

Installation

npm install flagmint-vuejs-feature-flags
TypeScript support is built-in with full type declarations included.

Quick Start

Vue 3 Setup

// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { createFlagmintPlugin } from 'flagmint-vuejs-feature-flags';

const app = createApp(App);

app.use(createFlagmintPlugin({
  apiKey: 'your-api-key',
  context: { user_id: 'abc123', country: 'US' },
  transportMode: 'auto',
  autoRefresh: true,
  previewMode: false
}));

app.mount('#app');

Vue 2 Setup

// main.js
import Vue from 'vue';
import { createFlagmintPlugin } from 'flagmint-vuejs-feature-flags';

Vue.use(createFlagmintPlugin({
  apiKey: 'your-api-key',
  context: { user_id: 'abc123', country: 'NG' },
  transportMode: 'auto',
  autoRefresh: true,
  previewMode: false
}));

new Vue({ render: h => h(App) }).$mount('#app');

Configuration Options

The createFlagmintPlugin accepts a FlagClientOptions object:
OptionTypeDefaultDescription
apiKeystringrequiredYour Flagmint API key
contextRecord<string, any>{}User attributes for targeting (e.g., user_id, email, country)
autoRefreshbooleantrueAutomatically refresh flags when context changes
refreshIntervalMsnumber30000Polling interval for HTTP mode (milliseconds)
persistContextbooleanfalseStore context in localStorage
enableOfflineCachebooleantrueEnable offline flag caching
cacheTTLnumber3600000Cache time-to-live (1 hour default)
transportMode'auto' | 'websocket' | 'long-polling''auto'Connection mode (auto tries WebSocket first)
previewModebooleanfalseLocal-only mode (no network calls)
onError(err: Error) => voidundefinedError callback handler
Use transportMode: 'auto' for the best experience - it automatically uses WebSocket with fallback to long-polling.

Using Flags

<template>
  <div>
    <div v-if="flags['dark-mode']">
      Dark mode is enabled! 🌙
    </div>
    <div v-if="flags['new-feature']">
      Check out our new feature!
    </div>
  </div>
</template>

<script setup>
import { useFlagClient, useFlagmintReady } from 'flagmint-vuejs-feature-flags';

// Wait for flags to load
await useFlagmintReady();

// Get reactive flag client
const flagClient = useFlagClient();
const flags = flagClient.getReactiveFlags();

// Or get individual flags
const darkMode = flagClient.getFlag('dark-mode', false);
</script>

Vue 3 - Options API

<template>
  <div>
    <div v-if="isDarkMode">Dark mode enabled</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isDarkMode: false
    };
  },
  async mounted() {
    await this.$flagmintReady;
    this.isDarkMode = this.$flagmint.getFlag('dark-mode', false);
  }
}
</script>

Vue 2 - Using Mixin

<template>
  <div>
    <div v-if="featureFlags['dark-mode']">
      Dark mode is on!
    </div>
  </div>
</template>

<script>
import { useFlagsMixin } from 'flagmint-vuejs-feature-flags/vue2/useFlags';

export default {
  mixins: [useFlagsMixin],
  mounted() {
    console.log(this.featureFlags['dark-mode']);
    console.log(this.getFlag('dark-mode', false));
  }
}
</script>

Vue 2 - Options API

<script>
export default {
  async mounted() {
    await this.$flagmintReady;
    const enabled = this.$flagmint.getFlag('dark-mode', false);
  }
}
</script>

Feature Component

Use the built-in <Feature> component for declarative flag checking:
<template>
  <div>
    <Feature flag="dark-mode">
      <div class="dark-theme">Dark mode is enabled! 🌙</div>
    </Feature>
    
    <Feature flag="beta-features">
      <div class="beta-badge">Beta Features Available</div>
    </Feature>
  </div>
</template>

<script>
import { Feature } from 'flagmint-vuejs-feature-flags/vue3/components';
// For Vue 2: import { Feature } from 'flagmint-vuejs-feature-flags/vue2/components';

export default {
  components: { Feature }
};
</script>

Reactive Flags

Get all flags as a reactive object that automatically updates:
// ✅ Recommended (Reactive)
const flags = this.$flagmint.getReactiveFlags();
console.log(flags['dark-mode']); // updates reactively when flag changes

// ⚠️ Non-reactive (useful for quick access)
const enabled = this.$flagmint.getFlag('dark-mode', false);

Updating Context

Update user context dynamically (triggers flag re-evaluation):
// Update context
this.$flagmint.updateContext({ 
  user_id: 'user123',
  plan: 'premium',
  country: 'US'
});

// Or merge with existing context
this.$flagmint.updateContext({ plan: 'enterprise' });
When autoRefresh: true, updating context automatically re-evaluates all flags with the new attributes.

Preview Mode (Local Testing)

Enable preview mode for local development without API calls:
createFlagmintPlugin({
  previewMode: true,
  context: { user_id: 'test-user' }
});

// Then load flags directly
flagClient.setFlags([
  {
    key: 'dark-mode',
    type: 'boolean',
    value: true,
    targeting_rules: []
  }
], {});
Preview mode shows a console warning in development. This mode is ideal for:
  • SDK testing
  • Storybook development
  • Static environments

Targeting Rules & Rollouts

Flags support sophisticated targeting with rules and segments:
{
  key: 'new-ui',
  type: 'boolean',
  value: true,
  targeting_rules: [
    // Direct attribute rule
    { type: 'rule', attribute: 'country', operator: 'eq', value: 'NG' },
    // Segment reference
    { type: 'segment', segment_id: 'premium-users' }
  ],
  rollout: {
    strategy: 'percentage',
    percentage: 50,
    salt: 'xyz'
  },
  segmentsById: {
    'premium-users': {
      id: 'premium-users',
      rules: [{ attribute: 'plan', operator: 'eq', value: 'pro', type: 'rule' }]
    }
  }
}

Supported Operators

OperatorDescription
eqEqual to
neqNot equal to
inIn array
ninNot in array
gtGreater than
ltLess than
existsAttribute exists
not_existsAttribute doesn’t exist

Rollout Strategies

Percentage Rollout
{
  strategy: 'percentage',
  percentage: 50,  // 50% of users get the feature
  salt: 'unique-salt'
}
Variant Rollout
{
  strategy: 'variant',
  variants: [
    { id: 'control', weight: 40 },
    { id: 'variant-a', weight: 30 },
    { id: 'variant-b', weight: 30 }
  ]
}

Real-time Updates

With WebSocket transport, flags update automatically when changed in Flagmint:
createFlagmintPlugin({
  transportMode: 'auto', // or 'websocket'
  apiKey: 'your-api-key',
  context: { user_id: 'abc123' }
});

// Flags will update in real-time without page refresh
Transport Modes:
  • auto - Tries WebSocket, falls back to long-polling
  • websocket - WebSocket only (fails if unavailable)
  • long-polling - HTTP polling only

Testing Your Integration

Use the Flagmint SDK Tester to verify your implementation:
npx flagmint-sdk-tester
The SDK Tester provides:
  • ✅ Both WebSocket and REST transport testing
  • ✅ Visual context builder
  • ✅ Protocol event logging
  • ✅ Flag evaluation verification
  • ✅ Network debugging

SDK Testing Tool

Test your Vue.js integration with our interactive testing tool

Advanced Usage

Manually Control Initialization

<script setup>
import { useFlagClient, useFlagmintReady } from 'flagmint-vuejs-feature-flags';

// Wait for initialization
const ready = await useFlagmintReady();

const client = useFlagClient();
const flags = client.getReactiveFlags();
</script>

Error Handling

createFlagmintPlugin({
  apiKey: 'your-api-key',
  onError: (error) => {
    console.error('Flagmint error:', error);
    // Log to your error tracking service
  }
});

Inject Pattern (Vue 3)

import { inject } from 'vue';

export default {
  setup() {
    const client = inject('__flagmint__');
    const feature = client?.getFlag('chat-enabled', false);
    return { feature };
  }
}

API Reference

Plugin Methods

getFlag(key: string, defaultValue?: any): any

Get a flag value (non-reactive).
const enabled = this.$flagmint.getFlag('dark-mode', false);

getReactiveFlags(): Record<string, any>

Get all flags as a reactive object.
const flags = this.$flagmint.getReactiveFlags();
// flags updates automatically when flags change

updateContext(context: Record<string, any>): void

Update user context and re-evaluate flags.
this.$flagmint.updateContext({ user_id: 'user123', plan: 'pro' });

setFlags(flags: Flag[], segmentsById: Record<string, Segment>): void

Manually set flags (useful in preview mode).
this.$flagmint.setFlags([flag1, flag2], segmentsById);

$flagmintReady: Promise<void>

Promise that resolves when flags are initialized.
await this.$flagmintReady;
// Flags are now loaded

Best Practices

For better performance and automatic updates, use getReactiveFlags() instead of getFlag() in templates.
<script setup>
const flags = useFlagClient().getReactiveFlags();
</script>

<template>
  <div v-if="flags['new-feature']">Feature content</div>
</template>
Always wait for $flagmintReady or useFlagmintReady() before accessing flags to avoid race conditions.
await this.$flagmintReady;
const value = this.$flagmint.getFlag('my-flag', false);
Always provide sensible defaults when calling getFlag() to handle loading states gracefully.
const theme = this.$flagmint.getFlag('theme', 'light'); // 'light' as default
Set transportMode: 'auto' to get WebSocket with automatic fallback to long-polling if WebSocket fails.

Example: Feature Toggle

<template>
  <div class="app">
    <Feature flag="dark-mode">
      <div class="dark-theme">
        <h1>Dark Mode Enabled 🌙</h1>
      </div>
    </Feature>
    
    <Feature flag="beta-features">
      <button @click="enableBeta">
        Try Beta Features
      </button>
    </Feature>
    
    <div v-if="flags['new-checkout']">
      <NewCheckoutFlow />
    </div>
    <div v-else>
      <LegacyCheckoutFlow />
    </div>
  </div>
</template>

<script setup>
import { useFlagClient, useFlagmintReady } from 'flagmint-vuejs-feature-flags';
import { Feature } from 'flagmint-vuejs-feature-flags/vue3/components';

await useFlagmintReady();

const client = useFlagClient();
const flags = client.getReactiveFlags();

const enableBeta = () => {
  client.updateContext({ beta_tester: true });
};
</script>

Example: A/B Testing

<template>
  <div>
    <div v-if="variant === 'control'">
      <OriginalFeature />
    </div>
    <div v-else-if="variant === 'variant-a'">
      <FeatureVariantA />
    </div>
    <div v-else-if="variant === 'variant-b'">
      <FeatureVariantB />
    </div>
  </div>
</template>

<script setup>
import { useFlagClient, useFlagmintReady } from 'flagmint-vuejs-feature-flags';

await useFlagmintReady();

const client = useFlagClient();
const variant = client.getFlag('experiment-design', 'control');
</script>

Roadmap

  • Segment evaluation
  • Rollout strategies (percentage & variant)
  • Preview/local-only mode
  • Composables and mixins
  • WebSocket + long-polling fallback
  • Feature component
  • SSR / Nuxt support
  • Variant analytics
  • Remote override via devtools

Troubleshooting

Symptoms: Flags return default valuesSolutions:
  • Verify your API key is correct
  • Check that you’re awaiting $flagmintReady or useFlagmintReady()
  • Ensure your network allows WebSocket connections to api.flagmint.com
  • Check browser console for errors
Symptoms: Changes in Flagmint dashboard don’t reflect in appSolutions:
  • Confirm transportMode is set to 'auto' or 'websocket'
  • Check WebSocket connection in browser DevTools (Network tab)
  • Verify autoRefresh: true is set
  • Ensure you’re using getReactiveFlags() not cached getFlag() calls
Symptoms: Type errors with flag methodsSolutions:
  • Ensure you’re using TypeScript 4.5+
  • Import types explicitly if needed:
    import type { FlagClientOptions } from 'flagmint-vuejs-feature-flags';
    

Support

npm Package

View on npm registry

SDK Tester

Test your integration

API Reference

Full API documentation

Contact Support

Get help from our team