Blog>
Snippets

Dynamic Configuration with TanStack Config

Provide an example of dynamically generating configurations based on runtime conditions or external inputs using TanStack Config.
import { createConfig } from '@tanstack/config';

// Defining a base configuration
const baseConfig = {
  apiUrl: 'https://example.com/api',
  mode: 'development'
};

// Function to dynamically adjust the configuration
function configureApp(environment) {
  // Creating a new config instance
  const appConfig = createConfig({
    ...baseConfig,
    // Overriding properties based on the runtime environment
    ...(environment === 'production' ? { apiUrl: 'https://prod.example.com/api', mode: 'production' } : {})
  });
  return appConfig;
}

// Example usage
const runtimeConfig = configureApp(process.env.NODE_ENV);
console.log(runtimeConfig);
This example demonstrates how to dynamically generate a configuration object using TanStack Config based on the runtime environment. It starts with a base configuration object, then uses a function to create a new configuration using `createConfig` from TanStack Config, conditionally overriding properties if the runtime environment is 'production'. This approach allows for flexible and environment-specific configurations.