JAVASCRIPT
Implement a Basic Node.js API Proxy Gateway
Create a simple Node.js Express proxy to securely route and manage requests to external APIs, abstracting their endpoints and potentially adding authentication or logging.
const express = require('express');
const axios = require('axios'); // For making HTTP requests to the target API
const cors = require('cors'); // If your frontend is on a different origin
const app = express();
const port = 3001;
// Configuration for the target API
const TARGET_API_BASE_URL = 'https://jsonplaceholder.typicode.com'; // Example public API
const API_KEY = process.env.TARGET_API_KEY || 'your_secret_api_key'; // For authenticating with target API
// Optional: Enable CORS for your proxy if frontend is on a different origin
app.use(cors());
// Middleware to add/modify headers for the target API (e.g., API Key)
app.use('/api/*', (req, res, next) => {
// Example: Add an API key to the request to the target API
req.headers['X-API-Key'] = API_KEY;
// Example: Remove sensitive headers that shouldn't be passed upstream
delete req.headers['cookie'];
delete req.headers['authorization']; // If auth is handled by the proxy
next();
});
// Proxy endpoint for /api/posts
app.get('/api/posts', async (req, res) => {
try {
const response = await axios.get(`${TARGET_API_BASE_URL}/posts`, { headers: req.headers });
res.json(response.data);
} catch (error) {
console.error('Error proxying posts API:', error.message);
res.status(error.response?.status || 500).json({ error: 'Failed to fetch posts from target API.' });
}
});
// Generic proxy for any path under /api/v1/*
// Note: This is a basic example, for robust API Gateway features consider libraries like http-proxy-middleware
app.all('/api/v1/*', async (req, res) => {
const targetPath = req.originalUrl.replace('/api/v1', ''); // Remove proxy prefix
const targetUrl = `${TARGET_API_BASE_URL}${targetPath}`;
try {
const response = await axios({
method: req.method,
url: targetUrl,
headers: req.headers, // Pass through relevant headers
data: req.body, // Pass through request body for POST/PUT
params: req.query // Pass through query parameters
});
res.status(response.status).json(response.data);
} catch (error) {
console.error(`Error proxying API request to ${targetUrl}:`, error.message);
res.status(error.response?.status || 500).json({ error: 'Failed to proxy request.' });
}
});
app.get('/', (req, res) => {
res.send('Basic API Proxy is running. Try /api/posts or /api/v1/users/1');
});
app.listen(port, () => {
console.log(`API Proxy running on http://localhost:${port}`);
console.log(`Proxying requests to ${TARGET_API_BASE_URL}`);
});
How it works: This Node.js Express snippet demonstrates building a basic API proxy. It acts as an intermediary, forwarding requests from a client to an external target API. This pattern helps abstract external API endpoints, hide API keys, manage CORS, or add common authentication headers before reaching the actual service. It uses `axios` to make the upstream calls and passes relevant request details like headers, body, and query parameters.