Help & Documentation
Welcome to the Feature Config help system. Find guides, tutorials, and reference documentation below.
Overview
Feature Config is a powerful feature flag management system that allows you to control, test, and rollout features with confidence.
What is Feature Config?
Feature Config enables you to:
- Control feature rollouts - Safely deploy features to specific users or percentages of your user base
- A/B test features - Compare different versions of features and measure their impact
- Manage configurations - Centralize application settings and feature toggles in one place
- Target users - Show different features based on user context (location, plan, custom attributes)
- Real-time updates - Change features instantly without code deployments or app updates
- Multi-environment support - Manage dev, staging, and production configurations independently
💡 Key Benefits
Risk Reduction
Test features with small user groups before full rollout. Instantly disable problematic features without code changes.
Faster Development
Deploy code with features disabled, then enable when ready. Decouple deployments from feature releases.
Better User Experience
Personalize features based on user context. Provide customized experiences for different user segments.
Operational Control
Instantly disable features causing issues. No code deployments or rollbacks required.
Analytics & Insights
Track feature usage with privacy-first analytics. Understand how features are evaluated across your user base.
Enterprise Security
Two-factor authentication, role-based access control, audit logging, and GDPR compliance built-in.
Common Use Cases
- Gradual Rollouts: Release features to 10% of users, then gradually increase to 100%
- Beta Testing: Give early access to specific users or user groups
- A/B Testing: Show different feature variations to measure effectiveness
- Regional Features: Enable features only in specific countries or regions
- Premium Features: Show advanced features only to paid users
- Kill Switches: Quickly disable features causing performance issues
- Environment Promotion: Test in dev, validate in staging, release to production
- Configuration Management: Manage API endpoints, limits, and settings without code changes
Quick Start Guide
Get up and running with Feature Config in four simple steps:
Step 1: Create a Site
Sites represent your applications or services. Each site can have multiple environments (dev, staging, prod).
Step 2: Add Environments
Create environments for different deployment targets. Each environment has independent feature configurations.
Step 3: Create Features
Define feature flags with values, types, and rules. Same feature can have different values per environment.
Step 4: Generate Tokens
Create environment-scoped API tokens. Each environment gets its own tokens for security isolation.
✅ What's Next?
Once you've completed these steps, you're ready to integrate Feature Config into your application. Check out the Integration section for code examples and best practices.
💡 Pro Tip: Use the hamburger menu (⋮) in tables for quick actions, and click on rows to navigate through your hierarchy!
Key Concepts
Understanding these core concepts will help you make the most of Feature Config.
Sites
Sites represent your applications or services. They provide top-level organization and ownership.
- Each site has an owner (user)
- Auto-creates a "prod" environment on creation
- Can have up to 10 environments
- Example: "E-commerce Platform", "Mobile App", "Admin Portal"
Environments
Environments are deployment targets within a site. They enable independent configuration per environment.
- Common names: dev, staging, prod
- Each has independent features and tokens
- Can be active, archived, or maintenance
- Example: test features in dev before promoting to prod
Features
Features are configuration values scoped to both site AND environment.
- Can be strings, numbers, booleans, or JSON objects
- Same feature key can have different values per environment
- Can be enabled or disabled
- Example: "new_checkout" = true in dev, false in prod
Rules
Rules determine when and how features are shown to users based on context.
- Based on user context (location, plan, etc.)
- Can use percentage rollouts
- Support complex AND/OR conditions
- Example: Show premium features to users with plan="pro"
Context
Context is information about the user or request that rules use for targeting.
- User properties (plan, location, age)
- Request properties (IP, user agent)
- Custom properties you define
- Example: {userId: "123", plan: "premium", country: "US"}
Tokens
Environment-scoped API tokens for secure access to feature configurations.
- Format: alm_env_{sitename}_{envname}_{random}
- Each environment has its own tokens
- Prevents dev tokens from accessing prod data
- Example: alm_env_ecommerce_dev_abc123...
How It Works Together
When your application requests a feature value:
- You provide the site ID, environment ID, and user context
- Feature Config evaluates all rules for each feature in that environment
- Rules are checked in order of priority (highest first)
- The first matching rule determines the feature value
- If no rules match, the default value is returned
- Results are cached for 5 minutes for performance
Dashboard
The dashboard provides an overview of your Feature Config system and quick access to common tasks.
What You'll See
- Getting Started Guide: Step-by-step instructions for new users
- Statistics: Total sites, environments, features, users, and active tokens
- Quick Actions: Fast access to create sites, add users, and test features
- Recent Activity: Shows recent changes from audit logs
- System Health: Database and cache status
💡 Pro Tips
- Use the "Test Features" button to quickly validate your feature configurations
- Check the health status to ensure your system is running properly
- The dashboard updates in real-time as you make changes
- Click on any stat card to navigate to the relevant section
Sites
Sites represent your applications or services. They provide top-level organization and ownership.
Creating Sites
- Click "Create Site" on the Sites page
- Enter a name and optional description
- Site is created with an auto-generated "prod" environment
- Click "Create Site" to complete
Site Navigation
Navigate through your sites with ease:
- Click any site row to navigate to its environments
- Use the hamburger menu (⋮) for site actions (edit, delete, etc.)
- Context is preserved as you navigate between pages
- Owner information shows who created and owns the site
Site Ownership
Every site has an owner:
- Owner is set to the user who created the site
- Provides clear accountability and audit trail
- Foundation for permission model
- Can be transferred to another user if needed
💡 Best Practices
- Use descriptive names that clearly identify the application
- Create separate sites for different applications or major services
- Add meaningful descriptions to document purpose and scope
- Click site rows to quickly navigate to environments
Environments
Environments are deployment targets within a site (e.g., dev, staging, prod). They enable independent configuration per environment.
Creating Environments
- Select a site from the dropdown
- Click "Create Environment"
- Enter a name (lowercase, alphanumeric, underscore, or hyphen only)
- Add optional description and tags
- Set initial status (active, archived, maintenance)
- Click "Create Environment"
Environment Status
- Active: Normal operation, accepting feature requests
- Archived: Inactive, preserved for historical reference
- Maintenance: Temporarily unavailable, planned maintenance
Environment Limits
Each site can have up to 10 environments (configurable via MAX_ENVIRONMENTS setting).
Environment-Scoped Features
The same feature key can have different values per environment:
- Test new features in dev without affecting prod
- Gradually roll out features from dev → staging → prod
- Each environment has independent rules and configurations
- Use environment-specific tokens for secure access
💡 Common Environment Names
- dev - Development environment for active coding
- staging - Pre-production for QA testing
- prod - Production environment for live users
- test - Automated testing environment
- sandbox - Isolated playground for experiments
Features
Features are configuration values scoped to both site AND environment. They can be toggles, settings, or any configurable value.
Feature Types
- STRING: Text values (e.g., "Welcome to our app!")
- NUMBER: Numeric values (e.g., 42, 3.14)
- BOOLEAN: True/false values (e.g., true, false)
- JSON: Complex objects (e.g., {"theme": "dark", "size": "large"})
Creating Features
- Select a site and environment from the dropdowns
- Click "Create Feature"
- Enter a unique key name
- Choose the appropriate type
- Set the default value
- Add a description and tags (optional)
- Click "Create Feature"
Feature Navigation
Navigate through your features seamlessly:
- Click any feature row to navigate to its rules
- Use the hamburger menu (⋮) for feature actions (edit, delete, etc.)
- Context is preserved - your selected site and environment remain active
- Enable/Disable toggle for quick feature activation control
Environment-Specific Features
Features are scoped to both site and environment:
- Same feature key can exist in multiple environments with different values
- Example: "new_checkout" = true in dev, false in prod
- Promotes features through environments as they're validated
- Each environment's features are completely independent
💡 Feature Naming Tips
- Use descriptive, lowercase names with underscores (e.g., "welcome_message")
- Group related features with prefixes (e.g., "ui_theme", "ui_layout")
- Avoid special characters and spaces
- Use consistent naming conventions across your site
- Click feature rows to quickly access their rules
Rule Builder
The Rule Builder allows you to create sophisticated targeting rules that determine when and how features are shown to users.
Rule Components
- Priority: Higher numbers take precedence (1-100)
- Conditions: Logic that determines when the rule applies (optional)
- Rollout: Percentage of matching users who get this rule (optional)
- Outcome: The value to return when the rule matches
Condition Types
- Equals: Exact match (e.g., country = "US")
- Not Equals: Does not match (e.g., plan ≠ "free")
- Contains: String contains value (e.g., email contains "@company.com")
- Greater/Less Than: Numeric comparisons (e.g., age > 18)
- In/Not In: Value in list (e.g., country in ["US", "CA", "MX"])
Complex Conditions
You can combine conditions using AND/OR logic:
- AND: All conditions must be true
- OR: Any condition can be true
- Nested: Combine AND/OR groups for complex logic
Rollout-Only Rules
You can create rules with only percentage rollouts (no conditions):
- Example: "50% of all users get true"
- Useful for gradual rollouts without targeting
- Deterministic - same user always gets same result
- Based on SHA-256 hashing of userId + feature key
💡 Rule Examples
- Geographic: Show different content based on user's country
- Plan-based: Premium features for paid users
- Gradual Rollout: 10% of users get new feature initially
- Beta Testing: New feature for users with beta flag enabled
- Combined: country = "US" AND 50% rollout
Test Console
The Test Console allows you to test your feature configurations with different user contexts without affecting real users.
How to Test
- Select a site and environment
- Select a feature to test
- Enter test context (user properties) in JSON format
- Optionally specify a user ID for consistent testing
- Click "Test Evaluation"
Test Results
The console shows you:
- Evaluated Value: What the user would receive
- Matched Rule: Which rule (if any) was applied
- Decision ID: Unique identifier for this evaluation
- Rollout Status: Whether the user was included in percentage rollouts
- Cache Status: Whether result was served from cache
💡 Testing Tips
- Test edge cases and boundary conditions
- Verify percentage rollouts with multiple user IDs
- Test with different context combinations
- Use consistent user IDs to test deterministic behavior
- Test in each environment to verify environment-specific configs
Analytics
Feature Analytics provides privacy-first insights into how your features are being evaluated and used.
What's Tracked
- Feature Evaluations: How many times each feature was evaluated
- Context Fields: Only fields actually checked by rules (privacy-first)
- Rule Performance: Which rules are matching and how often
- Trends Over Time: Daily aggregations showing usage patterns
Privacy-First Design
Analytics are designed with GDPR compliance in mind:
- Minimal Data Collection: Only context fields checked by rules
- No PII by Default: User IDs are hashed (SHA-256)
- Configurable Sampling: Reduce data volume while maintaining accuracy
- Short Retention: Configurable retention periods (default 90 days)
- Field Exclusion: Exclude sensitive fields from analytics
Analytics Dashboard
The analytics page shows:
- Summary Cards: Total evaluations, unique users, avg evaluations per user
- Trend Charts: Daily evaluation counts over time (Chart.js)
- Context Breakdown: Top context field values being evaluated
- Rule Performance: Which rules are matching most often
Performance Impact
- Fire-and-Forget API: Analytics calls don't block feature evaluation
- Batching: Client SDK batches 20 evaluations or 60 seconds
- Async Processing: Redis queue with background workers
- Low Overhead: <50ms API response time
💡 Analytics Use Cases
- Identify which features are most heavily used
- Understand which rules are matching in production
- Detect anomalies in evaluation patterns
- Optimize rules based on actual usage data
- Verify rollout percentages are working correctly
Webhooks
Webhooks allow you to receive real-time notifications when features, rules, or configurations change.
Webhook Events
Webhooks are triggered for these events:
- Feature Created: New feature added to an environment
- Feature Updated: Feature value or settings changed
- Feature Deleted: Feature removed from environment
- Rule Created: New rule added to a feature
- Rule Updated: Rule conditions or outcome changed
- Rule Deleted: Rule removed from feature
Creating Webhooks
- Navigate to Webhooks page
- Click "Create Webhook"
- Enter a name and description
- Provide the target URL (must be HTTPS in production)
- Select which events to subscribe to
- Optionally set a secret for signature verification
- Click "Create Webhook"
Webhook Payload
Each webhook request includes:
{
"event": "feature.updated",
"timestamp": "2025-10-18T12:00:00Z",
"siteId": "uuid",
"environmentId": "uuid",
"data": {
"feature": {...},
"changes": {...}
}
}
Security
- Secret Tokens: Verify webhook authenticity with HMAC-SHA256 signatures
- HTTPS Only: Production webhooks require secure connections
- Retry Logic: Failed deliveries are retried with exponential backoff
- Signature Header: X-Webhook-Signature header contains HMAC signature
Testing Webhooks
Use the built-in testing tools:
- Test Button: Send a test payload to your webhook
- Delivery Logs: View recent webhook deliveries and responses
- Test Payloads: See example payloads for each event type
💡 Webhook Use Cases
- Notify Slack channel when features change in production
- Trigger CI/CD pipeline to update configurations
- Log all configuration changes to external audit system
- Invalidate application caches when features update
- Send alerts when critical features are disabled
User Management
User management allows you to control access to the Feature Config admin interface with role-based permissions.
User Roles
- Admin: Full access to all features including user management, 2FA administration, and GDPR requests
- Editor: Can create and modify sites, environments, features, and rules
- Viewer: Read-only access to view configurations
Creating Users
- Click "Add User" on the Users page (admin only)
- Enter username, email, and password
- Select appropriate role
- Click "Create User"
- User will receive a welcome email (if email configured)
Two-Factor Authentication
Admin users are required to enable 2FA:
- Grace Period: 7 days to enable 2FA from account creation
- Methods: TOTP (authenticator app) or email codes
- Mandatory: After grace period, admins must enable 2FA to access dashboard
- Backup Codes: Generated for account recovery
Managing Users
Use the modern interface to manage users:
- Hamburger menu (⋮): Edit, change role, reset 2FA, delete user
- Search: Filter users by username or email (server-side search)
- Privacy: Email addresses hidden from list view (data minimization)
💡 Security Best Practices
- Require strong passwords for all users (min 8 characters)
- Enable 2FA for all admin accounts
- Grant minimum necessary permissions (principle of least privilege)
- Regularly review user access and remove inactive users
- Use audit logs to monitor user actions
API Tokens
API tokens provide secure, environment-scoped access for your applications to fetch feature configurations.
Environment-Scoped Tokens
Tokens are scoped to specific environments for security:
- Format: alm_env_{sitename}_{envname}_{random}
- Isolation: Dev tokens cannot access prod data
- Security: Each environment has its own tokens
- Traceability: Token usage is tracked per environment
Creating Tokens
- Select a site and environment
- Click "Create Token"
- Enter a description (e.g., "Mobile App - Dev")
- Set expiration date (optional)
- Click "Create Token"
- Copy token immediately - it won't be shown again
Token Security
- SHA-256 Hashing: Tokens are hashed before storage
- One-time Display: Plaintext token shown only at creation
- Rate Limiting: 100 requests/minute per token
- Expiration: Optional expiration dates for temporary access
Using Tokens
Include the token in your API requests:
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://features.almiro.se/api/v1/sites/{siteId}/environments/{envId}/features
Managing Tokens
Use the modern interface to manage tokens:
- Hamburger menu (⋮): Edit description, copy token, delete token
- Filter by environment: View tokens for specific environments
- Expiration tracking: See when tokens will expire
- Usage statistics: Monitor token usage per environment
💡 Token Security Best Practices
- Store tokens securely in environment variables
- Never commit tokens to version control
- Use separate tokens for each environment
- Set expiration dates for temporary access
- Rotate tokens regularly in production
- Revoke tokens that are no longer needed
- Monitor token usage for suspicious activity
Two-Factor Authentication (2FA)
Two-Factor Authentication adds an extra layer of security to your Feature Config account.
Available Methods
- TOTP (Time-based One-Time Password): Use authenticator apps like Google Authenticator, Authy, or 1Password
- Email Codes: Receive 6-digit codes via email (valid for 10 minutes)
Setting Up TOTP
- Navigate to Profile page
- Click "Enable 2FA"
- Select "Authenticator App"
- Scan QR code with your authenticator app
- Enter 6-digit verification code
- Save backup codes securely
Setting Up Email 2FA
- Navigate to Profile page
- Click "Enable 2FA"
- Select "Email Codes"
- Verify your email address
- Enter confirmation code sent to email
- Save backup codes securely
Login with 2FA
When 2FA is enabled:
- Enter username and password
- Enter 6-digit 2FA code (from app or email)
- Optionally check "Trust this device for 30 days"
- Click "Verify" to complete login
Trusted Devices
- 30-day Trust: Skip 2FA on trusted devices for 30 days
- Revoke Access: Remove trusted devices from Profile page
- Audit Trail: View all trusted devices with last used timestamps
Backup Codes
Backup codes provide account recovery if you lose access to your 2FA method:
- 8 single-use codes generated when enabling 2FA
- Use any backup code in place of 2FA code
- Each code can only be used once
- Generate new codes from Profile page
Admin 2FA Management
Admins can manage 2FA for all users:
- View Statistics: See 2FA adoption rates
- Disable 2FA: Reset 2FA for locked-out users
- Send Reminders: Remind users to enable 2FA
- Enforce 2FA: Require 2FA for all admin users
💡 2FA Best Practices
- Use TOTP (authenticator app) for better security than email
- Store backup codes in a secure password manager
- Never share backup codes or 2FA secrets
- Review trusted devices regularly and revoke unused ones
- Enable 2FA immediately for all admin accounts
GDPR Data Subject Rights
Feature Config provides built-in support for GDPR data subject rights requests (access, erasure, portability).
Available Request Types
- Access Request (Art. 15): Export all personal data for a user
- Erasure Request (Art. 17): Delete all personal data for a user ("Right to be Forgotten")
- Portability Request (Art. 20): Export data in machine-readable format (JSON)
Creating a GDPR Request
- Navigate to GDPR Requests page (admin only)
- Click "Create Request"
- Enter user identifier (username or email)
- Select request type
- Add optional notes
- Click "Submit Request"
Request Processing
Requests are processed automatically:
- Access/Portability: JSON file generated with all user data
- Erasure: User data anonymized or deleted (preserves referential integrity)
- Email Notification: User notified when request is complete
- Auto-Cleanup: Export files deleted after 30 days
What Data is Included
GDPR exports include:
- User account information (username, email, role)
- Sites owned by the user
- Audit log entries (actions performed)
- 2FA settings and trusted devices
- GDPR request history
Request Status
- Pending: Request submitted, awaiting processing
- Completed: Request processed successfully
- Failed: Request processing encountered an error
💡 GDPR Compliance Notes
- Requests must be processed within 30 days (GDPR requirement)
- All requests are logged in audit trail
- Export files are encrypted at rest
- Users can request access to their data at any time
- Erasure respects data retention requirements
White-Label / Branding
Customize the look and feel of Feature Config to match your brand with white-label branding options.
Branding Options
- Colors: Primary, secondary, accent, success, warning, error, info colors
- Alert Text Colors: Text colors for alert backgrounds (success, warning, error, info)
- Typography: Font families for headings and body text
- Logo: Custom logo URL
- Favicon: Custom favicon URL
- Company Name: Your organization name
Applying Branding
Branding is applied at the site level:
- Navigate to Sites page
- Select site to customize
- Open hamburger menu (⋮)
- Click "Edit Branding"
- Customize colors, fonts, and assets
- Preview changes in real-time
- Click "Save Branding"
Color Customization
Customize all interface colors:
- Primary Color: Main brand color for buttons, links
- Secondary Color: Supporting color for secondary actions
- Accent Color: Highlight color for important elements
- Success/Warning/Error: Alert background colors
- Success/Warning/Error Text: Alert text colors for proper contrast
- Background Colors: Primary, secondary, tertiary backgrounds
- Text Colors: Primary, secondary, muted text
WCAG Compliance
Branding includes WCAG contrast validation:
- Automatically checks color contrast ratios
- Warns about accessibility issues
- Ensures text remains readable with custom colors
- Validates alert text colors against background colors
💡 Branding Tips
- Use your brand guidelines for color selection
- Test colors in both light and dark themes
- Ensure sufficient contrast for accessibility
- Use high-resolution logos (SVG recommended)
- Preview changes before saving to ensure readability
Integration Overview
Learn how to integrate Feature Config into your applications with practical code examples and best practices.
Quick Links
Integration Pattern
All integrations follow this pattern:
- Initialize client with API token and base URL
- Fetch features for specific site + environment + context
- Evaluate features client-side for low latency
- Cache results for 5 minutes to reduce API calls
- Handle errors gracefully with default values
Frontend Integration
Choose the integration method that best fits your application:
📦 Vanilla JavaScript (No Dependencies)
Use our standalone JavaScript client - perfect for any web project!
Option 1: Link from your server
<script src="https://features.almiro.se/feature-config.js"></script>
<script>
const client = new FeatureConfigClient({
apiToken: 'your-token-here',
baseUrl: 'https://features.almiro.se/api/v1'
});
// Get all features for site + environment
client.getFeatures('site-id', 'env-id', { userId: '123', plan: 'premium' })
.then(features => console.log(features));
// Get specific feature
client.getFeature('site-id', 'env-id', 'welcome_message', 'Hello!', { userId: '123' })
.then(value => console.log(value));
// Check if feature is enabled
client.isFeatureEnabled('site-id', 'env-id', 'new_ui', { userId: '123' })
.then(enabled => console.log('New UI:', enabled));
</script>
Option 2: Download and self-host
Download the client file and include it in your project:
<script src="/js/feature-config.js"></script>
<script>
const client = new FeatureConfigClient({
apiToken: 'your-token-here',
baseUrl: 'https://features.almiro.se/api/v1'
});
</script>
✨ Features
- Zero dependencies - pure JavaScript
- Built-in caching (5 minutes default)
- Works in all modern browsers
- Async/await support
- Only ~4KB minified
⚛️ React Integration
For React applications, use a custom hook for better integration:
1. Install Dependencies
npm install axios
2. Create Feature Config Hook
// hooks/useFeatureConfig.js
import { useState, useEffect } from 'react';
import axios from 'axios';
const API_BASE = 'https://features.almiro.se/api/v1';
const API_TOKEN = process.env.REACT_APP_FEATURE_CONFIG_TOKEN;
export const useFeatureConfig = (siteId, environmentId, context = {}) => {
const [features, setFeatures] = useState({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchFeatures = async () => {
try {
setLoading(true);
const response = await axios.post(`${API_BASE}/evaluate`, {
siteId,
environmentId,
context
}, {
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
}
});
setFeatures(response.data.features || {});
setError(null);
} catch (err) {
setError(err.message);
console.error('Failed to fetch features:', err);
} finally {
setLoading(false);
}
};
fetchFeatures();
}, [siteId, environmentId, JSON.stringify(context)]);
const getFeature = (key, defaultValue = null) => {
return features[key]?.value ?? defaultValue;
};
const isFeatureEnabled = (key) => {
return getFeature(key, false) === true;
};
return { features, loading, error, getFeature, isFeatureEnabled };
};
3. Use in Your Components
// components/WelcomeMessage.js
import React from 'react';
import { useFeatureConfig } from '../hooks/useFeatureConfig';
const WelcomeMessage = ({ user }) => {
const { getFeature, isFeatureEnabled, loading } = useFeatureConfig(
'your-site-id',
'prod', // environment
{
userId: user.id,
plan: user.plan,
country: user.country
}
);
if (loading) return Loading...;
const welcomeMessage = getFeature('welcome_message', 'Welcome!');
const showPremiumBanner = isFeatureEnabled('premium_banner');
return (
{welcomeMessage}
{showPremiumBanner && 🎉 You have premium access!}
);
};
export default WelcomeMessage;
Backend Integration (Node.js/Express)
Here's how to integrate Feature Config into your Node.js backend with caching:
1. Create Feature Config Service
// services/FeatureConfigService.js
const axios = require('axios');
class FeatureConfigService {
constructor(apiToken, baseUrl = 'https://features.almiro.se/api/v1') {
this.apiToken = apiToken;
this.baseUrl = baseUrl;
this.cache = new Map();
this.cacheTimeout = 5 * 60 * 1000; // 5 minutes
}
async getFeatures(siteId, environmentId, context = {}) {
const cacheKey = `${siteId}:${environmentId}:${JSON.stringify(context)}`;
const cached = this.cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
return cached.data;
}
try {
const response = await axios.post(`${this.baseUrl}/evaluate`, {
siteId,
environmentId,
context
}, {
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
}
});
const features = response.data.features || {};
// Cache the result
this.cache.set(cacheKey, {
data: features,
timestamp: Date.now()
});
return features;
} catch (error) {
console.error('Failed to fetch features:', error);
return {};
}
}
async getFeature(siteId, environmentId, key, defaultValue = null, context = {}) {
const features = await this.getFeatures(siteId, environmentId, context);
return features[key]?.value ?? defaultValue;
}
async isFeatureEnabled(siteId, environmentId, key, context = {}) {
return await this.getFeature(siteId, environmentId, key, false, context) === true;
}
}
module.exports = FeatureConfigService;
2. Use in Express Routes
// routes/api.js
const express = require('express');
const FeatureConfigService = require('../services/FeatureConfigService');
const router = express.Router();
const featureConfig = new FeatureConfigService(process.env.FEATURE_CONFIG_TOKEN);
router.get('/dashboard', async (req, res) => {
const context = {
userId: req.user?.id,
plan: req.user?.plan,
country: req.user?.country
};
const showNewDashboard = await featureConfig.isFeatureEnabled(
'your-site-id',
'prod',
'new_dashboard',
context
);
const maxItems = await featureConfig.getFeature(
'your-site-id',
'prod',
'dashboard_max_items',
10,
context
);
res.render(showNewDashboard ? 'dashboard-v2' : 'dashboard-v1', { maxItems });
});
module.exports = router;
Python Integration
Here's a simple Python client for Feature Config:
# feature_config.py
import requests
import json
import time
from typing import Dict, Any
class FeatureConfigClient:
def __init__(self, api_token: str, base_url: str = "https://features.almiro.se/api/v1"):
self.api_token = api_token
self.base_url = base_url
self.cache = {}
self.cache_timeout = 300 # 5 minutes
def get_features(self, site_id: str, environment_id: str, context: Dict[str, Any] = None) -> Dict[str, Any]:
if context is None:
context = {}
cache_key = f"{site_id}:{environment_id}:{json.dumps(context, sort_keys=True)}"
if cache_key in self.cache:
cached = self.cache[cache_key]
if time.time() - cached['timestamp'] < self.cache_timeout:
return cached['data']
try:
response = requests.post(
f"{self.base_url}/evaluate",
json={"siteId": site_id, "environmentId": environment_id, "context": context},
headers={
"Authorization": f"Bearer {self.api_token}",
"Content-Type": "application/json"
},
timeout=5
)
response.raise_for_status()
features = response.json().get('features', {})
self.cache[cache_key] = {
'data': features,
'timestamp': time.time()
}
return features
except Exception as e:
print(f"Failed to fetch features: {e}")
return {}
def get_feature(self, site_id: str, environment_id: str, key: str, default_value: Any = None, context: Dict[str, Any] = None) -> Any:
features = self.get_features(site_id, environment_id, context)
return features.get(key, {}).get('value', default_value)
def is_feature_enabled(self, site_id: str, environment_id: str, key: str, context: Dict[str, Any] = None) -> bool:
return self.get_feature(site_id, environment_id, key, False, context) is True
# Usage example
if __name__ == "__main__":
client = FeatureConfigClient(api_token="your-token-here")
context = {"userId": "123", "plan": "premium"}
enabled = client.is_feature_enabled("site-id", "prod", "new_feature", context)
print(f"New feature enabled: {enabled}")
Integration Best Practices
Environment Setup
# .env file
FEATURE_CONFIG_TOKEN=your_token_here
FEATURE_CONFIG_URL=https://features.almiro.se/api/v1
FEATURE_CONFIG_SITE_ID=your-site-id
FEATURE_CONFIG_ENV=prod
Best Practices Checklist
Performance
- Cache feature values for 5-10 minutes
- Use batch evaluation for multiple features
- Implement request timeouts (5 seconds recommended)
- Leverage ETag headers for HTTP 304 responses
Error Handling
- Always provide default values
- Handle network failures gracefully
- Log errors for debugging
- Fallback to cached values on errors
Security
- Store tokens in environment variables
- Never commit tokens to version control
- Use HTTPS for all API calls
- Use environment-specific tokens (dev vs prod)
Context
- Pass relevant user context (plan, location, etc.)
- Use consistent user IDs for deterministic behavior
- Test with different context combinations
- Don't include sensitive data in context
✅ Need More Help?
Check the Test Console to experiment with different configurations, or review the Overview section for more information on how Feature Config works.