Blog>
Snippets

Securing Sensitive Configurations

Explain the best practices for securing sensitive information (API keys, credentials) with TanStack Config, possibly using environment variables and encryption techniques.
import { createConfig } from '@tanstack/config-react';

// Define your configuration schema
const configSchema = {
  apiUrl: '',
  apiKey: '',
};

// Initialize your configuration with environment variables
const myConfig = createConfig({
  schema: configSchema,
  defaults: {
    apiUrl: process.env.REACT_APP_API_URL,
    apiKey: process.env.REACT_APP_API_KEY
  }
});
This code demonstrates the initial setup of TanStack Config in a React project. It imports the `createConfig` function from '@tanstack/config-react' and defines a schema for the configuration. `createConfig` is then used to initialize the configuration, pulling `apiUrl` and `apiKey` from environment variables via `process.env`, ensuring sensitive data like API keys are not hardcoded into the source code.
const encrypt = (plaintext, secret) => {
  // Encryption logic here
  return encryptedText;
};

const decrypt = (encryptedText, secret) => {
  // Decryption logic here
  return decryptedText;
};
This code snippet provides placeholder functions for encrypting and decrypting sensitive information. In a real-world scenario, you would replace the comment placeholders with actual encryption and decryption logic, using a suitable cryptographic library. The `encrypt` function would be used to encrypt sensitive data before saving it, and the `decrypt` function would be used to decrypt the data when needed for use.
const secureConfig = {
  ...myConfig.defaults,
  apiKey: decrypt(myConfig.defaults.apiKey, 'your-secret-here')
};
This snippet demonstrates how to apply decryption to the sensitive data (`apiKey`) in the configuration using the `decrypt` function defined earlier. It spreads the existing default configurations and then overrides the `apiKey` property with the decrypted version, using a secret. This approach assumes the apiKey stored in the environment variables is encrypted and needs decryption before use in the application. The secret used for decryption should be stored securely.