Documentation Index
Fetch the complete documentation index at: https://docs.flagmint.com/llms.txt
Use this file to discover all available pages before exploring further.
Flagmint JavaScript SDK
The Flagmint JavaScript SDK is a framework-agnostic client for evaluating feature flags with pluggable caching and flexible transport strategies. It works seamlessly in both browser and Node.js server-side environments.Quick Start
Get up and running in minutes
React Integration
Framework-specific examples
Configuration
Customize caching and transport
API Reference
Complete method documentation
Key Features
- Framework-Agnostic — Works with React, Vue, vanilla JS, Node.js, and more
- Flexible Transport — WebSocket for real-time updates with automatic long-polling fallback
- Pluggable Caching — Built-in sync cache, async cache (Redis/filesystem), or custom implementations
- Server & Browser Support — Compatible with browser, Node.js, and React Native
- Type-Safe — Full TypeScript support with comprehensive type definitions
- Zero-Config Defaults — Works out of the box with sensible defaults
Installation
TypeScript Support: The SDK includes built-in TypeScript declarations with full type safety.
Quick Start
Configuration
FlagClientOptions
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | Required | Your environment API key |
context | Record<string, any> | {} | Initial evaluation context (user attributes, org, etc.) |
enableOfflineCache | boolean | true | Cache flags locally for offline resilience |
persistContext | boolean | false | Persist evaluation context across sessions |
cacheAdapter | CacheAdapter | Sync helper | Custom cache implementation |
transportMode | 'auto' | 'websocket' | 'long-polling' | 'auto' | Transport strategy for flag updates |
onError | (error: Error) => void | undefined | Callback for transport or initialization errors |
previewMode | boolean | false | Evaluate using rawFlags only, bypassing remote fetch |
rawFlags | Record<string, FlagValue> | undefined | Local-only flag definitions for preview mode |
deferInitialization | boolean | false | If true, initialization is deferred until ready() is called |
restEndpoint | string | Auto-detected | Custom REST evaluation endpoint |
wsEndpoint | string | Auto-detected | Custom WebSocket endpoint |
Endpoint auto-detection: The SDK automatically selects endpoints based on
NODE_ENV — production uses api.flagmint.com, staging uses staging-api.flagmint.com, and development defaults to localhost:3000. Override with restEndpoint and wsEndpoint if needed.Context Structure
Thecontext object should follow this structure:
Cache Adapters
Sync (Browser / In-Memory)
By default, the SDK uses a synclocalStorage-based helper in browsers or a Map in Node.js:
Async (Redis / File System)
Use the async helper for server-side or React Native:Custom Cache (Redis Example)
The default cache TTL is 24 hours. The
loadFlags function receives the TTL (in milliseconds) as a second argument so your custom adapter can respect it.Transport Modes
The SDK supports three transport strategies:| Mode | Latency | Resource Usage | Best For |
|---|---|---|---|
| WebSocket | Lowest (real-time) | Efficient | Real-time dashboards, live updates |
| Long-Polling | Medium | Higher | Simpler setup, firewall-friendly |
| Auto (default) | Lowest to Medium | Varies | Most applications (recommended) |
Transport Behavior
- WebSocket: Persistent connection for instant flag updates
- Long-Polling: Polls at 20-minute intervals with exponential backoff on failure (up to 60s max, 2x multiplier)
- Auto (default): Tries WebSocket first, falls back to long-polling if the WebSocket connection fails
Framework Integration Examples
React
The
subscribe() callback fires immediately with current flags (including cached flags), so your UI is populated before ready() even resolves.Node.js / Express
Vanilla JavaScript
Context Management
Updating Context
Update user context at any time to re-evaluate flags:updateContext() merges the new context with the existing context and re-fetches flags from the server. If the transport is unavailable, the context is still updated locally but flags will not reflect the change until the connection is restored.Persisting Context
Enable context persistence across sessions:Deferred Initialization
For scenarios where you need to set up the client before context is available:Error Handling
The SDK provides two mechanisms for handling errors:onError callback
Use the onError option to receive errors without wrapping ready() in a try/catch:
ready() rejection
ready() always rejects on transport failure, regardless of whether onError is set. Wrap it in a try/catch to prevent unhandled promise rejections:
Offline resilience summary
| Scenario | ready() | getFlags() | onError |
|---|---|---|---|
| Transport succeeds | Resolves | Fresh flags | Not called |
| Transport fails, cache exists | Rejects | Cached flags | Called |
| Transport fails, no cache | Rejects | {} (empty) | Called |
| Transport fails, cache expired (>24h) | Rejects | {} (empty) | Called |
Subscribing to flag updates
Usesubscribe() to react to flag changes in real time:
Preview Mode
For testing or preview environments where you want to bypass remote flag fetching:In preview mode, the client is immediately ready — no
ready() call is needed (though calling it is safe). Flags are evaluated locally against the provided context using the SDK’s built-in evaluation engine.API Reference
FlagClient Methods
ready(timeoutMs?: number): Promise<void>
Wait for the initial connection and flag synchronisation to complete. Rejects if the transport fails. Default timeout is 3000ms.
deferInitialization is true, calling ready() triggers initialization.
getFlags(): FeatureFlags<T>
Get all current flag values as a shallow copy.
getFlag<K>(key: K, fallback?: T): T
Get a single flag value with an optional fallback.
updateContext(context: C): Promise<void>
Merge new context with the existing context. Triggers a re-fetch of flags from the server.
subscribe(callback: (flags: FeatureFlags<T>) => void): () => void
Subscribe to flag changes. The callback fires immediately with current flags, then on every subsequent update. Returns an unsubscribe function.
destroy(): void
Close the transport connection, clear all subscribers, and clean up resources.
CacheAdapter Interface
Evaluation Helpers
The SDK includes low-level evaluation utilities:evaluateFlagValue(flag, context)
evaluateRollout(rollout, context)
isInSegment(context, segment)
rolloutUtils
SDK Tester Tool
Use the Flagmint SDK Tester for interactive testing:Troubleshooting
Client not connecting
- Verify your API key is correct
- Check network connectivity
- Review browser console for errors
- Ensure CORS is properly configured if using from browser
Flags not updating
- Check transport mode (WebSocket vs long-polling)
- Verify context is properly set with
updateContext() - Use
subscribe()to listen for flag changes - If using a custom cache adapter, verify your TTL isn’t too aggressive
ready() keeps rejecting
- Check that the Flagmint API is reachable from your environment
- If behind a firewall, try
transportMode: 'long-polling'(WebSocket may be blocked) - Wrap
ready()in a try/catch and fall back to cached flags — see Error Handling
Performance issues
- Consider using long-polling instead of WebSocket for high-traffic scenarios
- Implement proper cache TTLs with a custom cache adapter
- Use Redis caching for server-side applications
TypeScript errors
- Ensure you’re using the latest version of the SDK
- Check that your
tsconfig.jsonincludes proper module resolution - Use explicit type parameters:
client.getFlag<boolean>('flag', false)
Support & Resources
Documentation
Full platform documentation
GitHub Issues
Report bugs and issues
Email Support
Contact our support team
SDK Tester
Interactive testing tool