Blog>
Snippets

Creating Dynamic Configurations for Different Environments

Provide a code snippet that demonstrates how to set up TanStack Config to automatically select the appropriate settings based on the development, staging, or production environment.
// Define the base configuration object
const baseConfig = {
  apiUrl: 'https://api.example.com',
  enableDebug: false,
};

// Define environment-specific configurations
const environmentConfigs = {
  development: {
    apiUrl: 'https://dev-api.example.com',
    enableDebug: true,
  },
  staging: {
    apiUrl: 'https://staging-api.example.com',
    enableDebug: true,
  },
  production: {
    // Inherits the baseConfig as it is
  },
};

// Function to get the current environment
function getCurrentEnvironment() {
  // Replace this with logic to determine the current environment dynamically
  // e.g., based on process.env.NODE_ENV
  return 'development'; // For the sake of example
}

// Merge the base config with the environment-specific config
function getConfig() {
  const environment = getCurrentEnvironment();
  return { ...baseConfig, ...environmentConfigs[environment] };
}

// Usage
const config = getConfig();
console.log('Current config:', config);
This code snippet demonstrates how to create a dynamic configuration system for JavaScript projects that automatically selects the appropriate settings based on the current environment (development, staging, or production). It first defines a base configuration object and then overrides or extends it with environment-specific settings. The getCurrentEnvironment function is a placeholder for implementing logic to detect the current environment, which could be based on environment variables or any other relevant criteria. The getConfig function merges the base configuration with any overrides defined for the current environment, allowing for flexible and scalable project configurations.