🚀 How to Use Feature Flags in Apps
This guide explains how to integrate and use KalkaAI feature flags in your applications across different platforms and frameworks.
Table of Contents
Quick Start
1. Get Your API Credentials
- 1Access Dashboard: Navigate to your KalkaAI dashboard at
https://dashboard.kalkaai.com - 2Go to Environments: Click on "Environments" in the left sidebar
- 3Select Environment: Choose the appropriate environment for your use case:
- Development: For local development and testing
- Staging: For pre-production testing and QA
- Production: For live production applications
💡 How to choose? Start with Development for initial setup, then promote flags through Staging to Production as they're tested and ready.
- 4Get API Key:
- Click on the environment card to view its details
- Find the "API Key" section
- Click the copy button to copy your API key
- Format:
kka_[environment]_xxxxx
- 5Get Environment ID:
- The Environment ID is displayed in the same environment card
- Click the copy button to copy the Environment ID
- Format:
environment-id-string
Example credentials:
# Production KALKAAI_API_KEY=kka_production_1234567890abcdef KALKAAI_ENVIRONMENT_ID=prod-env-987654321 # Development KALKAAI_DEV_API_KEY=kka_development_abcdef1234567890 KALKAAI_DEV_ENVIRONMENT_ID=dev-env-123456789
⚠️ Security Note: Keep your API keys secure and never commit them to version control. Use environment variables or secure configuration management.
Client-Side Integration (React/Next.js)
Installation
npm install @kalkaai/js-sdk # or yarn add @kalkaai/js-sdk
Basic Setup
import { KalkaAI } from '@kalkaai/js-sdk';
// Initialize the client
const kalkaai = new KalkaAI({
apiKey: process.env.NEXT_PUBLIC_KALKAAI_API_KEY,
environmentId: process.env.NEXT_PUBLIC_KALKAAI_ENVIRONMENT_ID,
userId: 'user-123', // Optional: for user-specific flags
attributes: { // Optional: for attribute-based targeting
plan: 'premium',
region: 'us-east-1',
betaUser: true
}
});React Hook Usage
import { useFeatureFlag } from '@kalkaai/js-sdk/react';
function MyComponent() {
const { isEnabled, isLoading, variant } = useFeatureFlag('new-checkout-flow');
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
{isEnabled ? (
<NewCheckoutFlow variant={variant} />
) : (
<OldCheckoutFlow />
)}
</div>
);
}Server-Side Integration
Node.js/Express
const { KalkaAI } = require('@kalkaai/node-sdk');
const kalkaai = new KalkaAI({
apiKey: process.env.KALKAAI_API_KEY,
environmentId: process.env.KALKAAI_ENVIRONMENT_ID
});
app.get('/api/features', async (req, res) => {
const userId = req.user.id;
const userAttributes = {
plan: req.user.plan,
region: req.user.region
};
const isNewFeatureEnabled = await kalkaai.isEnabled(
'new-api-endpoint',
userId,
userAttributes
);
res.json({ newFeatureEnabled: isNewFeatureEnabled });
});Next.js API Routes
// pages/api/features.js or app/api/features/route.js
import { KalkaAI } from '@kalkaai/js-sdk';
const kalkaai = new KalkaAI({
apiKey: process.env.KALKAAI_API_KEY,
environmentId: process.env.KALKAAI_ENVIRONMENT_ID
});
export async function GET(request) {
const { searchParams } = new URL(request.url);
const userId = searchParams.get('userId');
const flags = await kalkaai.getAllFlags(userId, {
plan: 'premium'
});
return Response.json({ flags });
}Mobile App Integration
React Native
npm install @kalkaai/react-native-sdk
import { KalkaAI } from '@kalkaai/react-native-sdk';
const kalkaai = new KalkaAI({
apiKey: 'your-api-key',
environmentId: 'your-env-id',
userId: 'user-123'
});
// In your component
const [featureEnabled, setFeatureEnabled] = useState(false);
useEffect(() => {
kalkaai.isEnabled('new-feature').then(setFeatureEnabled);
}, []);iOS (Swift)
import KalkaAISDK
let kalkaai = KalkaAI(
apiKey: "your-api-key",
environmentId: "your-env-id",
userId: "user-123"
)
kalkaai.isEnabled("new-feature") { enabled in
if enabled {
// Show new feature
} else {
// Show fallback
}
}Android (Kotlin)
implementation 'com.kalkaai:android-sdk:1.0.0'
val kalkaai = KalkaAI.Builder()
.apiKey("your-api-key")
.environmentId("your-env-id")
.userId("user-123")
.build()
kalkaai.isEnabled("new-feature") { enabled ->
if (enabled) {
// Show new feature
} else {
// Show fallback
}
}Real-Time Updates
WebSocket Connection
import { KalkaAI } from '@kalkaai/js-sdk';
const kalkaai = new KalkaAI({
apiKey: process.env.NEXT_PUBLIC_KALKAAI_API_KEY,
environmentId: process.env.NEXT_PUBLIC_KALKAAI_ENVIRONMENT_ID,
realTimeUpdates: true // Enable real-time updates
});
// Listen for flag changes
kalkaai.onFlagUpdate('new-feature', (enabled, variant) => {
// Update your UI immediately
});React Hook with Real-Time
import { useFeatureFlag } from '@kalkaai/js-sdk/react';
function MyComponent() {
const { isEnabled, variant, isLoading } = useFeatureFlag('new-feature', {
realTime: true // Automatically update when flag changes
});
// Component re-renders automatically when flag is updated
return (
<div>
{isEnabled ? <NewFeature variant={variant} /> : <OldFeature />}
</div>
);
}Analytics & Tracking
Tracking Flag Usage
// Track when a feature is used
kalkaai.track('feature-used', {
flagKey: 'new-checkout-flow',
userId: 'user-123',
properties: {
variant: 'blue-button',
conversionValue: 99.99
}
});
// Track custom events
kalkaai.track('purchase-completed', {
userId: 'user-123',
properties: {
amount: 149.99,
featureFlags: kalkaai.getActiveFlags()
}
});A/B Testing Metrics
// Automatically track conversion metrics
const { isEnabled, variant, trackConversion } = useFeatureFlag('ab-test-checkout');
const handlePurchase = (amount) => {
// Track conversion with value
trackConversion('purchase', { value: amount });
// Continue with purchase logic
processPurchase(amount);
};Configuration
Environment Variables
# .env.local NEXT_PUBLIC_KALKAAI_API_KEY=kka_development_your_api_key NEXT_PUBLIC_KALKAAI_ENVIRONMENT_ID=dev-env-id # .env.production NEXT_PUBLIC_KALKAAI_API_KEY=kka_production_your_api_key NEXT_PUBLIC_KALKAAI_ENVIRONMENT_ID=prod-env-id # Server-side only (no NEXT_PUBLIC prefix) KALKAAI_API_KEY=kka_production_server_key KALKAAI_ENVIRONMENT_ID=prod-env-id
Advanced Configuration
const kalkaai = new KalkaAI({
apiKey: process.env.NEXT_PUBLIC_KALKAAI_API_KEY,
environmentId: process.env.NEXT_PUBLIC_KALKAAI_ENVIRONMENT_ID,
// Optional configurations
timeout: 5000, // API timeout in milliseconds
retryAttempts: 3, // Number of retry attempts
cacheTimeout: 300000, // Cache timeout (5 minutes)
realTimeUpdates: true, // Enable WebSocket updates
// Default user attributes
defaultAttributes: {
platform: 'web',
version: '1.0.0'
},
// Logging
logLevel: 'warn', // 'debug', 'info', 'warn', 'error'
// Fallback values for offline mode
fallbacks: {
'new-feature': false,
'beta-feature': true
}
});Best Practices
Flag Naming Conventions
- Use descriptive names:
new-checkout-flowinstead offlag1 - Use kebab-case:
user-profile-redesign - Include context:
mobile-app-dark-mode
Deployment Strategy
Always test your feature flags in the development environment first.
Use percentage-based rollouts to test with a subset of staging users.
Start with 5-10% of users, then gradually increase based on metrics.
Error Handling
// Always provide fallback values
const { isEnabled, isLoading, error } = useFeatureFlag('new-feature', {
fallback: false // Default value if API fails
});
if (error) {
// Continue with fallback behavior
}
// Or use try-catch for synchronous calls
try {
const enabled = await kalkaai.isEnabled('new-feature');
return enabled;
} catch (error) {
return false; // Safe fallback
}Troubleshooting
Common Issues
API Key Authentication Failed
Error: 401 Unauthorized
Solution:
- • Verify your API key is correct and active
- • Ensure you're using the right environment (dev/staging/prod)
- • Check that the API key hasn't expired
Flag Not Found
Error: Feature flag 'my-flag' not found
Solution:
- • Verify the flag exists in your dashboard
- • Check you're targeting the correct environment
- • Ensure flag name matches exactly (case-sensitive)
Real-Time Updates Not Working
Issue: Flag changes don't update immediately
Solution:
- • Enable
realTimeUpdates: true - • Check WebSocket connection in browser dev tools
- • Verify firewall doesn't block WebSocket connections
Debug Mode
// Enable debug logging
const kalkaai = new KalkaAI({
apiKey: 'your-api-key',
environmentId: 'your-env-id',
logLevel: 'debug' // Shows detailed logs
});
// Check SDK status
console.log('SDK Status:', kalkaai.getStatus());
console.log('Active Flags:', kalkaai.getActiveFlags());
console.log('Connection Status:', kalkaai.isConnected());Getting Help
If you're still experiencing issues:
- • Check our dashboard status page
- • Review the browser console for error messages
- • Contact our support team with your API key and error details
- • Include your SDK version and environment information