Skip to content

Feature Flags Plugin โ€‹

Introduction โ€‹

The Better Auth Feature Flags plugin provides a complete feature flag management system integrated directly with your authentication layer. Control feature rollouts, run A/B tests, and manage user experiences with powerful targeting rules and real-time evaluation.

Key Features โ€‹

Core Capabilities

  • ๐Ÿš€ Dynamic Control - Enable/disable features without deployments
  • ๐ŸŽฏ Advanced Targeting - Rule-based targeting with complex conditions
  • ๐Ÿงช A/B Testing - Multiple variants with deterministic assignment
  • ๐Ÿ”’ Security First - Role-based access, audit logging, and privacy controls
  • โšก High Performance - <100ms P99 latency at 100K+ RPS
  • ๐Ÿข Multi-tenant - Organization-level isolation and management

Why Feature Flags? โ€‹

Feature flags enable modern software development practices:

Progressive Rollouts โ€‹

Roll out new features gradually to minimize risk:

typescript
// Start with 10% of users
await updateFlag("new-feature", { rolloutPercentage: 10 });

// Monitor metrics, then increase
await updateFlag("new-feature", { rolloutPercentage: 50 });

// Full rollout when confident
await updateFlag("new-feature", { enabled: true, rolloutPercentage: 100 });

Instant Kill Switch โ€‹

Disable problematic features immediately:

typescript
// Emergency disable
await updateFlag("problematic-feature", { enabled: false });

Targeted Experiences โ€‹

Deliver personalized features based on user attributes:

typescript
// Premium features for paid users
{
  rules: [
    {
      conditions: {
        attribute: "subscription",
        operator: "equals",
        value: "premium",
      },
      value: true,
    },
  ];
}

How It Works โ€‹

The plugin evaluates flags in priority order:

  1. User Overrides - Highest priority for specific users
  2. Targeting Rules - Condition-based evaluation
  3. Percentage Rollout - Gradual release using consistent hashing
  4. Default Value - Fallback when no conditions match

Architecture โ€‹

Plugin Integration โ€‹

The feature flags plugin integrates seamlessly with Better Auth:

typescript
import { betterAuth } from "better-auth";
import { featureFlags } from "better-auth-feature-flags";

const auth = betterAuth({
  plugins: [
    featureFlags({
      // Configuration
    }),
  ],
});

Storage Options โ€‹

Choose the storage backend that fits your needs:

StorageUse CasePerformancePersistence
DatabaseProduction deploymentsHighYes
MemoryDevelopment/testingVery HighNo
RedisHigh-scale distributed appsVery HighYes

Database Schema โ€‹

The plugin creates these tables in your database:

sql
-- Core tables
featureFlag        -- Flag definitions
flagRule           -- Targeting rules
flagOverride       -- User-specific overrides

-- Analytics tables (optional)
flagEvaluation     -- Usage tracking
flagAudit          -- Change history

Flag Types โ€‹

Support for different data types:

Boolean Flags โ€‹

Simple on/off switches:

typescript
{ type: "boolean", defaultValue: false }

String Flags โ€‹

Text values for configuration:

typescript
{ type: "string", defaultValue: "blue" }

Number Flags โ€‹

Numeric values for limits or thresholds:

typescript
{ type: "number", defaultValue: 100 }

JSON Flags โ€‹

Complex configuration objects:

typescript
{
  type: "json",
  defaultValue: {
    theme: "dark",
    layout: "grid"
  }
}

Evaluation Context โ€‹

The plugin automatically collects context for evaluation:

typescript
interface EvaluationContext {
  // User information
  userId?: string;
  email?: string;
  role?: string;
  organizationId?: string;

  // Device information (opt-in)
  device?: "mobile" | "tablet" | "desktop";
  browser?: string;
  os?: string;

  // Custom attributes
  attributes?: Record<string, any>;
}

Performance โ€‹

Optimized for production scale:

Performance Metrics

  • Evaluation Latency: <10ms (P50), <100ms (P99)
  • Throughput: 100,000+ evaluations/second
  • Cache Hit Rate: >95% with proper configuration
  • Database Queries: 1-2 per uncached evaluation

Optimization Strategies โ€‹

  1. In-memory caching with configurable TTL
  2. Bulk evaluation for multiple flags
  3. Connection pooling for database efficiency
  4. Consistent hashing for O(1) rollout decisions

Security & Privacy โ€‹

Built with security and privacy by design:

Security Features โ€‹

  • โœ… Input validation and sanitization
  • ๐Ÿ›ก๏ธ Protection against injection attacks
  • ๐Ÿšฆ Rate limiting on evaluation endpoints
  • ๐Ÿ‘ค Role-based access control for admin APIs
  • ๐Ÿ“ Audit logging for compliance

Privacy Controls โ€‹

  • ๐Ÿ” Opt-in data collection
  • โš™๏ธ Configurable context attributes
  • ๐Ÿšซ No PII collection by default
  • ๐Ÿ‡ช๐Ÿ‡บ GDPR-compliant data handling
  • ๐Ÿ“… Automatic data retention policies

Use Cases โ€‹

Feature Rollouts โ€‹

typescript
// Gradual rollout to minimize risk
await createFlag({
  key: "new-dashboard",
  rolloutPercentage: 10, // Start with 10%
  defaultValue: false,
});

A/B Testing โ€‹

typescript
// Test different variations
await createFlag({
  key: "checkout-flow",
  variants: {
    control: { buttonText: "Buy Now" },
    variant_a: { buttonText: "Purchase" },
    variant_b: { buttonText: "Get Started" },
  },
});

Beta Features โ€‹

typescript
// Limited access for beta testers
await createFlag({
  key: "beta-feature",
  rules: [
    {
      conditions: {
        attribute: "role",
        operator: "equals",
        value: "beta-tester",
      },
      value: true,
    },
  ],
  defaultValue: false,
});

Maintenance Mode โ€‹

typescript
// Instant feature disable for emergencies
await createFlag({
  key: "payment-processing",
  enabled: false, // Kill switch
  defaultValue: true,
});

Multi-tenancy โ€‹

Full support for multi-tenant applications:

typescript
featureFlags({
  multiTenant: {
    enabled: true,
    useOrganizations: true,
  },
});

// Flags are isolated per organization
const orgFlag = await getFlag("feature", "org-123");

Analytics Integration โ€‹

Track feature usage and performance:

typescript
featureFlags({
  analytics: {
    trackUsage: true,
    trackPerformance: true,
  },
});

// Query usage data
const stats = await getFlagStats("new-feature");
// { evaluations: 10000, enabled: 6000, conversion: 0.15 }

Best Practices โ€‹

Important Guidelines

  1. Start Small - Begin with low rollout percentages
  2. Monitor Metrics - Track performance and errors during rollouts
  3. Use Descriptive Keys - Choose clear, consistent naming conventions
  4. Document Flags - Include descriptions for team understanding
  5. Clean Up - Remove obsolete flags regularly
  6. Test Thoroughly - Verify flag behavior in all environments

Comparison โ€‹

How Better Auth Feature Flags compares to alternatives:

FeatureBetter AuthLaunchDarklyUnleashSplit
Authentication Integrationโœ… NativeโŒ SeparateโŒ SeparateโŒ Separate
Self-hostedโœ…โŒโœ…โŒ
Multi-tenantโœ…โœ…โš ๏ธโœ…
A/B Testingโœ…โœ…โœ…โœ…
Real-time Updates๐Ÿ”œ Plannedโœ…โœ…โœ…
Audit Loggingโœ…โœ…โœ…โœ…
PricingFree$$$$$$$$

Browser Support โ€‹

Works in all modern browsers and runtimes:

  • โœ… Chrome 90+
  • โœ… Firefox 88+
  • โœ… Safari 14+
  • โœ… Edge 90+
  • โœ… Node.js 18+
  • โœ… Deno 1.30+
  • โœ… Bun 1.0+
  • โœ… Cloudflare Workers

TypeScript Support โ€‹

Full TypeScript support with type inference:

typescript
// Type-safe flag evaluation
const isDarkMode = await featureFlags.isEnabled<boolean>("dark-mode");

// Typed variants
type CheckoutVariant = {
  buttonColor: string;
  buttonText: string;
};

const variant = await featureFlags.getVariant<CheckoutVariant>("checkout-test");

License โ€‹

This plugin is part of the Better Auth ecosystem and follows the same licensing terms as the main Better Auth package.

Getting Started โ€‹

Ready to add feature flags to your application?

Quick Links