Blog>
Snippets

Initializing TanStack Config in a Node.js Application

Show how to set up TanStack Config in a Node.js environment, including basic configuration loading and environment-specific settings.
const { Config } = require('@tanstack/config-node');
const path = require('path');
Require the necessary TanStack Config module for Node.js and the path module for handling file paths.
const environment = process.env.NODE_ENV || 'development';
Determine the current environment. Defaults to 'development' if the NODE_ENV variable is not set.
const config = new Config({
  files: [
    path.resolve(process.cwd(), `config/${environment}.json`),
    path.resolve(process.cwd(), 'config/default.json')
  ]
});
Initialize TanStack Config with environment-specific and default configuration files. The configuration files are expected to be JSON.
async function loadConfig() {
  await config.load();
  console.log('Configuration loaded:', config.get());
}
Define an asynchronous function to load the configuration using the Config instance and then log the loaded configuration.
loadConfig().catch((error) => {
  console.error('Failed to load configuration:', error);
});
Invoke the loadConfig function to attempt loading the configurations and catch any errors that might occur during the process.