JAVASCRIPT
Secure Server-Side API Key Management and Usage in Node.js
Learn to securely store and use third-party API keys on the server-side in a Node.js Express application using environment variables, preventing client-side exposure.
// server.js (Node.js with Express)
require('dotenv').config(); // Load environment variables from .env file
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;
// Retrieve API key from environment variables
const THIRD_PARTY_API_KEY = process.env.THIRD_PARTY_API_KEY;
const THIRD_PARTY_API_BASE_URL = 'https://api.thirdparty.com'; // Example URL
if (!THIRD_PARTY_API_KEY) {
console.error('THIRD_PARTY_API_KEY is not defined in environment variables!');
process.exit(1); // Exit if critical key is missing
}
app.get('/fetch-external-data', async (req, res) => {
try {
// Make a request to a third-party API using the securely stored key
const response = await axios.get(`${THIRD_PARTY_API_BASE_URL}/data`, {
headers: {
'Authorization': `Bearer ${THIRD_PARTY_API_KEY}`, // Or 'x-api-key' depending on API
'Accept': 'application/json'
},
params: {
// any query parameters
query: req.query.q || 'default'
}
});
res.json(response.data);
} catch (error) {
console.error('Error fetching data from third-party API:', error.message);
res.status(500).json({ message: 'Failed to fetch external data' });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
console.log('To test: curl http://localhost:3000/fetch-external-data?q=example');
});
// .env file example (in the same directory as server.js):
// THIRD_PARTY_API_KEY="your_super_secret_api_key_here"
How it works: This Node.js snippet demonstrates the secure handling of third-party API keys by storing them as environment variables (e.g., in a `.env` file) and accessing them server-side. This approach prevents exposing sensitive keys to client-side code, which could be exploited. An Express route then uses this key to make requests to an external API, acting as a secure proxy for client applications.