// index.js or app.js // ------------------ // In a real application, you would load dotenv at the very beginning // to ensure environment variables are available throughout your app. // For production, ensure these variables are set directly in your hosting environment. import 'dotenv/config'; // For Node.js, install with `npm install dotenv` and use `node -r dotenv/config your_app.js` or `import 'dotenv/config'` // Access API keys from environment variables const MY_API_KEY = process.env.ORG_API_KEY; const ANOTHER_SERVICE_SECRET = process.env.ANOTHER_SERVICE_SECRET; function makeSecureApiCall(endpoint, data) { if (!MY_API_KEY) { console.error("ORG_API_KEY environment variable is not set."); return Promise.reject(new Error("API key missing.")); } // Example of using the API key in a fetch request return fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${MY_API_KEY}` // Common pattern for API key authentication // Or sometimes: 'x-api-key': MY_API_KEY }, body: JSON.stringify(data) }) .then(response => { if (!response.ok) { throw new Error(`API call failed: ${response.status} ${response.statusText}`); } return response.json(); }) .catch(error => { console.error(`Error during API call to ${endpoint}:`, error); throw error; }); } // How to set environment variables (e.g., in .env file for local development): // -------------------------------------------------------------------------- // .env file (DO NOT COMMIT THIS FILE TO VERSION CONTROL): // ORG_API_KEY="your_super_secret_api_key_123" // ANOTHER_SERVICE_SECRET="another_secret_value_xyz" // In a shell before running your app: // export ORG_API_KEY="your_super_secret_api_key_123" // export ANOTHER_SERVICE_SECRET="another_secret_value_xyz" // node index.js // Example Usage: // (async () => { // try { // const result = await makeSecureApiCall("https://api.example.com/data", { item: "new item" }); // console.log("API call successful:", result); // } catch (error) { // console.error("API call failed:", error.message); // } // })();