Building a Feature Flag System in Node.js with Redis and Middleware
Feature flags (also known as feature toggles) allow you to enable or disable functionality without deploying new code. They are invaluable for A/B testing, phased rollouts, and operational control in production. In this article, you’ll learn how to implement a feature flag system in Node.js using Redis and Express middleware.
Why Use Feature Flags?
Feature flags help you:
- Deploy risky features safely
- Run experiments (A/B testing)
- Enable features for specific users
- Control feature availability without redeploying
Step 1: Project Setup
npm init -y
npm install express redis
Step 2: Redis Client Setup
// redisClient.js
const redis = require('redis');
const client = redis.createClient();
client.on('error', (err) => console.error('Redis Error:', err));
client.connect();
module.exports = client;
Step 3: Middleware for Feature Flags
// featureFlagMiddleware.js
const client = require('./redisClient');
const featureFlag = (flagName) => {
return async (req, res, next) => {
try {
const enabled = await client.get(`feature:${flagName}`);
if (enabled === 'true') {
return next();
} else {
return res.status(403).json({ message: 'Feature disabled' });
}
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Feature check failed' });
}
};
};
module.exports = featureFlag;
Step 4: Usage in Routes
// server.js
const express = require('express');
const featureFlag = require('./featureFlagMiddleware');
const client = require('./redisClient');
const app = express();
app.get('/', (req, res) => {
res.send('Main API');
});
app.get('/beta-feature', featureFlag('beta-feature'), (req, res) => {
res.send('Beta feature is active!');
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Step 5: Toggle Feature Flags in Redis
Enable a feature in Redis CLI or with any Redis GUI tool:
SET feature:beta-feature true
Disable it with:
SET feature:beta-feature false
Enhancements
- Enable features for specific user IDs or roles
- Implement flag variants for A/B testing
- Create a dashboard for toggling flags
- Use JSON structures in Redis for more complex rules
Conclusion
A feature flag system gives you fine-grained control over your application’s behavior in production. With Redis as your flag store and lightweight middleware in Node.js, you can scale this system to meet the needs of large teams and complex deployments.
If you found this helpful, consider supporting me: buymeacoffee.com/hexshift