Blog>
Snippets

Using Environment Variables with TanStack Config

Show how to securely use environment variables in TanStack Config to manage sensitive information like API keys.
// Define the configuration utilizing environment variables
const config = {
  apiBaseUrl: process.env.REACT_APP_API_BASE_URL,
  apiKey: process.env.REACT_APP_API_KEY
};
This snippet demonstrates how to define a configuration object in JavaScript, leveraging process.env to securely access environment variables. REACT_APP_API_BASE_URL and REACT_APP_API_KEY are placeholders for the actual environment variables holding sensitive information such as the base URL for your API and the API key, respectively. Such practices prevent hardcoding sensitive details in the codebase, adding a layer of security and flexibility.
// Usage of the config object to make a fetch call
fetch(`${config.apiBaseUrl}/data`, {
  headers: {
    'Authorization': `Bearer ${config.apiKey}`
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Here, the previously defined config object is used in a fetch request to demonstrate how the API base URL and API key environment variables could be utilized in an application. By inserting these values directly into the fetch call, we maintain the security of sensitive information while ensuring that our application can dynamically adapt to different environments (e.g., development, testing, production) without code changes.