Add feature flags to an AlpineJS project using the OpenFeature Standard.
npm install alpinejs-openfeature> [!WARNING]
> This plugin was created for demonstration and testing purposes only. It is not recommended to use this plugin in a production environment.
Add feature flags to an AlpineJS project using the OpenFeature Standard.
> [!NOTE]
> This plugin is currently limited to only the DevCycle Provider.
``html
defer
src="https://unpkg.com/alpinejs-openfeature@latest/dist/openfeature.min.js"
>
`
`shell
yarn add -D alpinejs-openfeature
npm install -D alpinejs-openfeature
`
`js
import Alpine from "alpinejs";
import openfeature from "alpinejs-openfeature";
import openfeature from "alpinejs-openfeature";
Alpine.plugin(openfeature);
Alpine.start();
`
To use this plugin, first include the x-openfeature directive within your main component element, identify your vendor, and provide your Client Key:
`html
x-data
x-openfeature:[VENDOR]='{ "key": "[CLIENT_KEY]", "options": {}}'
>
Replace
[VENDOR] with the name of your vendor in all lowercase (e.g. "devcycle") and [CLIENT_KEY] with your relevant vendor key (e.g. DevCycle Client Key). This initializes the feature flag provider and allows the use of feature flag checks within your application.Using Feature Flags
Feature flags are utilized via special magic methods
$stringFlag and $booleanFlag. These methods allow you to retrieve and act upon the values of your feature flags dynamically.- Boolean Flags: Use
$booleanFlag('flag_key', default_value) to evaluate a boolean flag. Here flag_key is the identifier for your flag, and default_value is the fallback value used if the flag cannot be fetched.
- String Flags: Use $stringFlag('flag_key', 'default_value') to retrieve the value of a string flag, with similar parameters as above.`html
The 'Boolean' feature flag is enabled!
The 'String' feature flag says " class="font-bold"
x-text="$stringFlag('string', 'default')"
> >"
The 'Boolean' feature flag is disabled.
`Handling Disconnections and Defaults
If there is a disconnection or an issue fetching the feature flags, the plugin automatically falls back to default values defined in your code. This ensures that your application can gracefully handle missing or unavailable feature flag data and continue functioning with predefined behaviors.
Complete Example
`html
AlpineJS OpenFeature Feature Flags Demo App
Featuring DevCycle's Web Provider
The 'Boolean' feature flag is enabled!
The 'String' feature flag says " class="font-bold"
x-text="$stringFlag('string', 'default')"
> >"
The 'Boolean' feature flag is disabled.
``> [!TIP]
> If you are building an AlpineJS plugin, consider using the AlpineJS Plugin Template created by Mark Mead that this repository is based upon.