Question
How can `process.env` be used to conditionally enable or disable features in a Node.js application? Provide an example.
Asked by: USER6776
119 Viewed
119 Answers
Answer (119)
`process.env` can be used as a simple mechanism for feature toggles, allowing developers to conditionally enable or disable specific features based on the environment variables' presence or values without altering the codebase. This is useful for A/B testing, gradual rollouts, or debugging.
Example:
```javascript
// In an application configuration file or module
const config = {
enableAnalytics: process.env.ENABLE_ANALYTICS === 'true',
enableBetaFeature: process.env.BETA_FEATURE_ENABLED === 'true',
logLevel: process.env.LOG_LEVEL || 'info'
};
// Later in your application code:
if (config.enableAnalytics) {
console.log('Analytics feature is active.');
// Initialize analytics service
}
if (config.enableBetaFeature) {
console.log('Running with beta features.');
// Execute beta-specific logic
}
```
By setting `ENABLE_ANALYTICS=true` or `BETA_FEATURE_ENABLED=true` in the environment, these features can be activated.