JAVASCRIPT
Creating a Simple API Proxy with Node.js Express for Security and Aggregation
Set up a basic Node.js Express API proxy to secure sensitive API keys, abstract external services, and potentially aggregate multiple API responses.
const express = require('express');
const fetch = require('node-fetch'); // Requires 'node-fetch' for older Node.js versions, built-in in Node.js 18+
require('dotenv').config(); // For managing environment variables
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON request bodies
app.use(express.json());
// Simple proxy endpoint for an external API
app.get('/api/external-data', async (req, res) => {
try {
const externalApiKey = process.env.EXTERNAL_API_KEY; // Keep API key hidden from client
const externalApiUrl = 'https://api.thirdparty.com/data';
// Construct query parameters if needed
const queryParams = new URLSearchParams(req.query).toString();
const url = `${externalApiUrl}?api_key=${externalApiKey}&${queryParams}`;
const response = await fetch(url);
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Proxy Error:', error);
res.status(500).json({ error: 'Failed to fetch data from external API' });
}
});
// Example of aggregating multiple APIs
app.get('/api/aggregated-dashboard', async (req, res) => {
try {
const userResponse = await fetch('https://api.internal.com/users/1');
const productResponse = await fetch('https://api.external.com/products?limit=5&api_key=' + process.env.EXTERNAL_API_KEY);
const [userData, productData] = await Promise.all([
userResponse.json(),
productResponse.json()
]);
res.json({ user: userData, recentProducts: productData });
} catch (error) {
console.error('Aggregation Error:', error);
res.status(500).json({ error: 'Failed to aggregate data' });
}
});
app.listen(PORT, () => {
console.log(`API Proxy running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to create a simple API proxy. It serves as an intermediary between your client-side application and external APIs. This pattern is invaluable for several reasons: it securely hides sensitive API keys from the client-side, allows you to abstract complex external API structures behind a simpler interface, and enables aggregation of data from multiple external services into a single response, reducing the number of requests a client needs to make. Environment variables are used to manage API keys securely.