Blog>
Snippets

Asynchronous Loading of Configurations with TanStack Config

Showcase how to asynchronously load environment-specific configurations using TanStack Config, ensuring secure and efficient runtime configuration.
import { createConfig } from 'tanstack-config';

// Define the async function to load configuration based on the environment
async function loadConfig() {
  let configUrl = '';
  switch (process.env.NODE_ENV) {
    case 'development':
      configUrl = '/config/development.json';
      break;
    case 'production':
      configUrl = '/config/production.json';
      break;
    default:
      configUrl = '/config/default.json';
  }
  const response = await fetch(configUrl);
  const configData = await response.json();
  return configData;
}

// Use TanStack Config to asynchronously load the environment-specific configurations
export const appConfig = createConfig({
  loadConfigs: [loadConfig],
});
This code snippet sets up asynchronous loading of environment-specific configurations using TanStack Config. It defines an asynchronous function 'loadConfig' which determines the appropriate configuration file URL based on the current environment. It then fetches this configuration file, parses it into JSON, and returns the configuration data. TanStack Config's 'createConfig' function is used to integrate the asynchronous loading function, ensuring that your application configurations are dynamically loaded at runtime.