Tutorial: Enable conditional features with a custom filter in a JavaScript application
Feature flags can use feature filters to enable features conditionally. To learn more about feature filters, see Tutorial: Enable conditional features with feature filters.
The example used in this tutorial is based on the Node.js application introduced in the feature management quickstart. Before proceeding further, complete the quickstart to create a Node.js application with a Beta feature flag. Once completed, you must add a custom feature filter to the Beta feature flag in your App Configuration store.
In this tutorial, you'll learn how to implement a custom feature filter and use the feature filter to enable features conditionally. We are using the Node.js console app as an example, but you can also use the custom feature filter in other JavaScript applications.
Prerequisites
Implement a custom feature filter
You've added a custom feature filter named Random with a Percentage parameter for your Beta feature flag in the prerequisites. Next, you implement the feature filter to enable the Beta feature flag based on the chance defined by the Percentage parameter.
Open the file app.js and add the
RandomFilter
with the following code.class RandomFilter { name = "Random"; evaluate(context) { const percentage = context.parameters.Percentage; const randomNumber = Math.random() * 100; return randomNumber <= percentage; } }
You added a
RandomFilter
class that has a single method namedevaluate
, which is called whenever a feature flag is evaluated. Inevaluate
, a feature filter enables a feature flag by returningtrue
.You set the name to of
RandomFilter
to Random, which matches the filter name you set in the Beta feature flag in Azure App Configuration.Register the
RandomFilter
when creating theFeatureManager
.const fm = new FeatureManager(ffProvider, {customFilters: [new RandomFilter()]});
Feature filter in action
When you run the application the configuration provider will load the Beta feature flag from Azure App Configuration. The result of the isEnabled("Beta")
method will be printed to the console. As the RandomFilter
is implemented and used by the Beta feature flag, the result will be True
50 percent of the time and False
the other 50 percent of the time.
Running the application will show that the Beta feature flag is sometimes enabled and sometimes not.
Beta is enabled: true
Beta is enabled: false
Beta is enabled: false
Beta is enabled: true
Beta is enabled: true
Beta is enabled: false
Beta is enabled: false
Beta is enabled: false
Beta is enabled: true
Beta is enabled: true
Next steps
To learn more about the built-in feature filters, continue to the following tutorials.