7.7.1. Create Custom Feature Flag
In this chapter, you'll learn how to create a custom feature flag in Medusa.
Why Create a Custom Feature Flag?#
As explained in the Feature Flags chapter, feature flags allow the Medusa team to ship new features that are still under development and testing, but not ready for production or wide use yet.
You can also create custom feature flags for your Medusa project or plugin to control the availability of experimental or in-development features. Feature flags allow you to test features in staging, and only enable them in production when they are ready.
How to Create a Custom Feature Flag#
1. Define the Feature Flag#
To create a custom feature flag, you need to define it in a new file under the src/feature-flags
directory of your Medusa project or plugin. The file must export a configuration object.
For example, to define a feature flag that enables a blog feature, create the file src/feature-flags/blog.ts
with the following content:
The feature flag configuration is an object having the following properties:
key
stringdefault_val
booleanenv_key
stringdescription
string2. Hide Features Behind the Flag#
Next, you can build the features you want to hide behind the feature flag.
To build backend customizations around feature flags, you can either:
- Conditionally run code blocks based on the feature flag status;
- Conditionally load files if the feature flag is not enabled.
For client customizations, such as admin widgets, you can use the Feature Flags API route.
3. Toggle Feature Flag#
To enable or disable your custom feature flag, you can either add it to your medusa-config.ts
file:
Or set the environment variable for the feature flag:
Afterwards, make sure to run migrations if your feature flag requires database changes.
If you're disabling a feature flag, make sure to roll back any migrations that depend on it first.
Write Tests for Features Behind Flags#
If you're writing integration tests for features hidden behind feature flags, you can enable the feature flag's environment variable in your integration test using the env
option.
For example:
Then, the Medusa application will load your customizations hidden behind the feature flag as part of the integration tests.