npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kanishkvats/feature-flag-sdk

v1.0.0

Published

Universal SDK for feature flag management with real-time updates via Socket.IO

Downloads

70

Readme

Feature Flag SDK

npm version Downloads MIT License

A powerful, real-time SDK for managing feature flags with live updates, intelligent rollouts, and audience targeting. Perfect for feature releases, A/B testing, and gradual deployments.

Features

Real-time Updates - Socket.IO-powered live flag changes
🎯 Smart Targeting - Boolean, percentage rollout, and segment-based rules
Local Evaluation - Fast, reliable flag checks with no server round-trips
🔐 Secure - API key authentication and encrypted connections
📦 Universal - Works in Node.js, Browsers (via REST)
🧪 TypeScript Support - Full type definitions included
📊 Battle-tested - Production-ready with proper error handling

Installation

npm install feature-flag-sdk

Or with yarn:

yarn add feature-flag-sdk

Quick Start

Node.js / CommonJS

const { FeatureFlagClient } = require('feature-flag-sdk');

async function main() {
  const client = new FeatureFlagClient({
    baseUrl: 'http://localhost:3001',
    apiKey: process.env.FEATURE_FLAG_API_KEY
  });

  await client.init();

  // Check if a flag is enabled for a user
  const enabled = client.isEnabled('new-checkout', 'user-123', { 
    plan: 'premium',
    country: 'US'
  });

  if (enabled) {
    console.log('✅ New checkout flow active!');
  }

  // Handle live updates
  client.on('update', (flags) => {
    console.log('Flags updated:', flags);
  });

  // Cleanup
  client.close();
}

main().catch(console.error);

ES Modules

import { FeatureFlagClient } from 'feature-flag-sdk';

const client = new FeatureFlagClient({
  baseUrl: 'http://localhost:3001',
  apiKey: process.env.FEATURE_FLAG_API_KEY
});

await client.init();

API Reference

Constructor: new FeatureFlagClient(options)

Options:

| Option | Type | Required | Description | |--------|------|----------|-------------| | baseUrl | string | ✓ | Feature flag server base URL | | apiKey | string | ✗ | API key for authentication | | socketUrl | string | ✗ | Socket.IO endpoint (defaults to baseUrl) | | onUpdate | function | ✗ | Callback when flags update |

Example:

const client = new FeatureFlagClient({
  baseUrl: 'https://flags.example.com',
  apiKey: 'ff_sk_prod_xxx',
  onUpdate: (flags) => console.log('Flags updated!', flags)
});

Methods

await init()

Loads flags from the server and establishes a Socket.IO connection for live updates.

await client.init();
console.log('✅ Client initialized');

isEnabled(flagName, userId, attributes = {})

Evaluates a flag locally. Supports three evaluation types:

Boolean Flags:

const enabled = client.isEnabled('dark-mode');

Percentage Rollout (Canary/Gradual Rollout):

// Enables for 25% of users (deterministic hash-based)
const enabled = client.isEnabled('new-ui', 'user-123');

Segment Targeting:

const enabled = client.isEnabled('premium-feature', 'user-456', {
  plan: 'premium',
  signupDate: '2024-01-01'
});
// Returns true if user matches segment rules

getFlag(flagName)

Returns the raw flag object or null.

const flag = client.getFlag('new-checkout');
console.log(flag);
// {
//   name: 'new-checkout',
//   type: 'percentage',
//   enabled: true,
//   rolloutPercentage: 50,
//   rules: []
// }

close()

Closes the Socket.IO connection and cleanup resources.

client.close();

on(event, callback)

Listen for client events.

client.on('update', (flags) => {
  console.log('Flags updated:', flags);
});

client.on('connect', () => {
  console.log('✅ Connected to flag server');
});

client.on('error', (error) => {
  console.error('❌ Connection error:', error);
});

Flag Types

1. Boolean Flags

Simple on/off toggles for features.

client.isEnabled('feature-name'); // true or false

2. Percentage Rollout

Gradual rollout to a percentage of users (deterministic).

// 30% of users based on consistent hashing
client.isEnabled('new-feature', 'user-id', {});

3. Segment Rules

Target specific user groups based on attributes.

client.isEnabled('premium-tier', 'user-id', {
  subscription: 'premium',
  country: 'US',
  beta: true
});

Examples

Express Integration

import express from 'express';
import { FeatureFlagClient } from 'feature-flag-sdk';

const app = express();
const flagClient = new FeatureFlagClient({
  baseUrl: process.env.FLAG_SERVER_URL,
  apiKey: process.env.FLAG_API_KEY
});

app.use(async (req, res, next) => {
  req.flags = flagClient;
  next();
});

app.get('/checkout', (req, res) => {
  const useNewCheckout = req.flags.isEnabled(
    'new-checkout-flow',
    req.user.id,
    { tier: req.user.tier }
  );

  res.json({ newCheckout: useNewCheckout });
});

await flagClient.init();
app.listen(3000);

React / Frontend

// Evaluate flags on backend, send to frontend
// Example: Express endpoint
app.get('/api/features', (req, res) => {
  res.json({
    darkMode: flagClient.isEnabled('dark-mode', req.user.id),
    betaUI: flagClient.isEnabled('beta-ui', req.user.id, {
      betaTester: req.user.betaTester
    })
  });
});

// Use in React
function App() {
  const [features, setFeatures] = useState({});

  useEffect(() => {
    fetch('/api/features')
      .then(r => r.json())
      .then(setFeatures);
  }, []);

  return (
    <div>
      {features.darkMode && <button>Dark Mode</button>}
      {features.betaUI && <BetaUIComponent />}
    </div>
  );
}

Error Handling

const client = new FeatureFlagClient({...});

client.on('error', (error) => {
  console.error('Connection error:', error.message);
  // Gracefully handle errors
});

try {
  await client.init();
} catch (error) {
  console.error('Failed to initialize:', error);
  // Fallback to default flag values
}

TypeScript Support

import { FeatureFlagClient, FlagOptions } from 'feature-flag-sdk';

const options: FlagOptions = {
  baseUrl: 'http://localhost:3001',
  apiKey: process.env.FLAG_API_KEY,
};

const client = new FeatureFlagClient(options);

const isEnabled: boolean = client.isEnabled(
  'my-feature',
  'user-123',
  { role: 'admin' }
);

Performance & Best Practices

Do:

  • Cache flag values in your application
  • Use deterministic user IDs (not session tokens)
  • Evaluate flags locally for instant response
  • Listen for update events to refresh cache

Don't:

  • Call init() multiple times
  • Pass random user IDs (breaks percentage rollout consistency)
  • Evaluate flags before await init() completes
  • Store sensitive data in flag attributes

Environment Variables

# .env
FLAG_SERVER_URL=https://flags.example.com
FLAG_API_KEY=ff_sk_prod_xxxxx

Support & Troubleshooting

| Issue | Solution | |-------|----------| | Connection refused | Check baseUrl and flag server status | | Auth failures | Verify apiKey is valid | | Stale flags | Ensure Socket.IO connection is active | | Inconsistent rollout | Use consistent user IDs (not random) |

Contributing

Contributions welcome! Please...

  1. Fork the repository
  2. Create a feature branch
  3. Add tests
  4. Submit a PR

License

MIT - see LICENSE for details


Need Help?