Blog>
Snippets

Feature Toggles with Environment Selectors in RTK 2.0

Create a feature toggling system by using environment selectors to determine which features are enabled or disabled based on the runtime environment.
const featureFlags = {
    feature1: process.env.NODE_ENV === 'production',
    feature2: process.env.NODE_ENV === 'development'
};
Define a featureFlags object where the keys represent feature names and the values are conditions based on the NODE_ENV environmental variable. For example, 'feature1' is only enabled in production environment while 'feature2' is enabled in development.
// Example of using feature flags in code
if (featureFlags.feature1) {
    console.log('Feature 1 is enabled.');
} else {
    console.log('Feature 1 is disabled.');
}
Using the featureFlags object to conditionally execute code. Here, we check if 'feature1' is enabled, and then perform actions based on that condition.
<div id="feature-container">
    <!-- Feature Module Placeholder -->
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var featureContainer = document.getElementById('feature-container');
        if (featureFlags.feature1) {
            featureContainer.innerHTML = '<p>Feature 1 Content</p>';
        }
        if (featureFlags.feature2) {
            featureContainer.innerHTML += '<p>Feature 2 Content</p>';
        }
    });
</script>
HTML structure with a placeholder for feature modules, and JavaScript to dynamically load content into the placeholder based on the feature flags.
/* Example CSS for feature styling */
#feature-container p {
    color: #333;
    font-weight: bold;
}
#feature-container .disabled {
    color: #999;
}
CSS styles for the feature container and its content. It includes a style for a 'disabled' class that can be added to indicate disabled features.