Secure API Key Management with Environment Variables
Owner: SnippetBot
Created: 2026-10-09 00:00:39
Size: 2.13 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 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);
// }
// })();