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:
// 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:
// Emergency disable
await updateFlag("problematic-feature", { enabled: false });
Targeted Experiences โ
Deliver personalized features based on user attributes:
// 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:
- User Overrides - Highest priority for specific users
- Targeting Rules - Condition-based evaluation
- Percentage Rollout - Gradual release using consistent hashing
- Default Value - Fallback when no conditions match
Architecture โ
Plugin Integration โ
The feature flags plugin integrates seamlessly with Better Auth:
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:
Storage | Use Case | Performance | Persistence |
---|---|---|---|
Database | Production deployments | High | Yes |
Memory | Development/testing | Very High | No |
Redis | High-scale distributed apps | Very High | Yes |
Database Schema โ
The plugin creates these tables in your database:
-- 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:
{ type: "boolean", defaultValue: false }
String Flags โ
Text values for configuration:
{ type: "string", defaultValue: "blue" }
Number Flags โ
Numeric values for limits or thresholds:
{ type: "number", defaultValue: 100 }
JSON Flags โ
Complex configuration objects:
{
type: "json",
defaultValue: {
theme: "dark",
layout: "grid"
}
}
Evaluation Context โ
The plugin automatically collects context for evaluation:
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 โ
- In-memory caching with configurable TTL
- Bulk evaluation for multiple flags
- Connection pooling for database efficiency
- 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 โ
// Gradual rollout to minimize risk
await createFlag({
key: "new-dashboard",
rolloutPercentage: 10, // Start with 10%
defaultValue: false,
});
A/B Testing โ
// Test different variations
await createFlag({
key: "checkout-flow",
variants: {
control: { buttonText: "Buy Now" },
variant_a: { buttonText: "Purchase" },
variant_b: { buttonText: "Get Started" },
},
});
Beta Features โ
// 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 โ
// Instant feature disable for emergencies
await createFlag({
key: "payment-processing",
enabled: false, // Kill switch
defaultValue: true,
});
Multi-tenancy โ
Full support for multi-tenant applications:
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:
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
- Start Small - Begin with low rollout percentages
- Monitor Metrics - Track performance and errors during rollouts
- Use Descriptive Keys - Choose clear, consistent naming conventions
- Document Flags - Include descriptions for team understanding
- Clean Up - Remove obsolete flags regularly
- Test Thoroughly - Verify flag behavior in all environments
Comparison โ
How Better Auth Feature Flags compares to alternatives:
Feature | Better Auth | LaunchDarkly | Unleash | Split |
---|---|---|---|---|
Authentication Integration | โ Native | โ Separate | โ Separate | โ Separate |
Self-hosted | โ | โ | โ | โ |
Multi-tenant | โ | โ | โ ๏ธ | โ |
A/B Testing | โ | โ | โ | โ |
Real-time Updates | ๐ Planned | โ | โ | โ |
Audit Logging | โ | โ | โ | โ |
Pricing | Free | $$$ | $$ | $$$ |
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:
// 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
- Quickstart Guide - Get up and running in 5 minutes
- Configuration - Detailed configuration options
- API Reference - Complete API documentation
- Client SDK - Frontend integration guide