Environment-based Configuration with TanStack Config
Showcase how to use TanStack Config to manage different configurations for development, testing, and production environments using environment variables.
import { defineConfig, loadConfig } from 'tanstack-config';
// Define the base configuration
const baseConfig = defineConfig({
API_URL: 'http://api.example.com',
FEATURE_TOGGLE: false,
});
Defines the base configuration using `defineConfig` from TanStack Config, which includes settings that are common across all environments such as the base API_URL and a feature toggle.
const env = process.env.NODE_ENV;
// Define environment-specific configurations
const envConfigs = {
development: {
API_URL: 'http://dev.api.example.com',
DEBUG_MODE: true,
},
production: {
API_URL: 'https://api.example.com',
DEBUG_MODE: false,
},
test: {
API_URL: 'http://test.api.example.com',
DEBUG_MODE: true,
},
};
Creates an object to hold environment-specific configurations. It uses `process.env.NODE_ENV` to determine the current environment and adjusts settings like the API_URL and DEBUG_MODE based on whether the environment is development, production, or test.
const config = loadConfig({
configs: [baseConfig, envConfigs[env] || {}],
});
Loads the final configuration by merging the base configuration with the environment-specific configuration using `loadConfig`. It falls back to an empty object if no environment-specific configuration is found, ensuring the base configuration is always loaded.
console.log(`Current Environment: ${env}`);
console.log(`API_URL: ${config.API_URL}`);
console.log(`DEBUG_MODE: ${config.DEBUG_MODE}`);
Outputs the current environment and the resulting configuration values for `API_URL` and `DEBUG_MODE` to the console. This illustrates how the final configuration reflects both the base settings and any environment-specific overrides.