Blog>
Snippets

Dynamic Configuration Using Environment Variables

Illustrate how to dynamically adjust configurations at runtime using environment variables with TanStack Config and TypeScript.
import { defineConfig } from 'tanstack-config';

export const config = defineConfig({
  // Example of accessing NODE_ENV for environment-specific configurations
  env: process.env.NODE_ENV,

  // Dynamically setting the API URL based on the deployment environment
  apiUrl: process.env.NODE_ENV === 'production' ? 'https://api.example.com' : 'https://dev.api.example.com',

  // Using environment variables for sensitive information
  apiKey: process.env.API_KEY
});
This code snippet demonstrates how to use TanStack Config with TypeScript for managing environment-specific configurations dynamically. It leverages environment variables such as 'NODE_ENV' and 'API_KEY' to adjust settings based on the runtime environment (e.g., production or development). We use the 'defineConfig' method from TanStack Config to create a configuration object, 'config', where we conditionally set the 'apiUrl' based on whether the environment is production or development. Additionally, it securely incorporates sensitive information such as an 'apiKey' by fetching it from the environment variables.