Blog>
Snippets

Environment-Specific Configuration with TanStack Config

Use TanStack Config to manage multiple configuration files for different environments (development, staging, production) securely, avoiding common pitfalls such as hardcoding sensitive information.
// Define base configuration common to all environments
const baseConfig = {
  apiBaseUrl: '',
  logging: false,
  retries: 3
};
This piece initializes a base configuration object with settings common across all environments such as a placeholder API base URL, logging disabled by default, and a default number of retries for failed requests.
// Extend baseConfig with environment-specific settings
const developmentConfig = {
  ...baseConfig,
  apiBaseUrl: 'http://localhost:3000',
  logging: true
};

const productionConfig = {
  ...baseConfig,
  apiBaseUrl: 'https://api.example.com',
  logging: false
};
Here, we create two configuration objects for development and production environments by spreading the baseConfig and overriding or extending it with environment-specific properties like the API base URL and logging preferences.
// Select the appropriate configuration based on NODE_ENV
const config = process.env.NODE_ENV === 'production' ? productionConfig : developmentConfig;
This code snippet demonstrates how to dynamically select the correct environment configuration by checking the NODE_ENV environment variable. It defaults to developmentConfig for any environment other than production.
// Usage of environment variables for sensitive configurations
const secretConfig = {
  apiKey: process.env.API_KEY
};

// Merge the selected config with secretConfig
const finalConfig = {
  ...config,
  ...secretConfig
};
To avoid hardcoding sensitive information such as API keys, this example demonstrates extracting such values from environment variables and incorporating them into the final configuration object by merging them with the environment-specific configuration.