JAVASCRIPT
Simple Node.js Proxy for Client-Side API Requests
Create a basic Node.js Express server to act as a proxy for external API requests, effectively bypassing CORS issues and securely handling API keys on the server-side.
const express = require('express');
const fetch = require('node-fetch'); // For Node.js, install with `npm install node-fetch@2` for CommonJS or newer for ESM
const cors = require('cors'); // For Node.js, install with `npm install cors`
const app = express();
const PORT = process.env.PORT || 3000;
// Use CORS middleware to allow requests from your frontend origin(s)
app.use(cors({ origin: 'http://localhost:8080' })); // Replace with your frontend URL
// Define your external API base URL and sensitive API key
const EXTERNAL_API_BASE_URL = 'https://api.example.com';
const API_KEY = process.env.EXTERNAL_API_KEY; // Store securely, e.g., in .env
app.get('/api/proxy/:endpoint', async (req, res) => {
const { endpoint } = req.params;
const queryParams = new URLSearchParams(req.query).toString();
const externalUrl = `${EXTERNAL_API_BASE_URL}/${endpoint}?${queryParams}`;
try {
const response = await fetch(externalUrl, {
headers: {
'Authorization': `Bearer ${API_KEY}` // Securely pass API key from server
}
});
if (!response.ok) {
const errorBody = await response.text();
return res.status(response.status).send(`External API error: ${errorBody}`);
}
const data = await response.json();
res.json(data); // Send data back to client
} catch (error) {
console.error('Proxy error:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});
How it works: This Node.js snippet sets up a simple Express server to act as an API proxy. It's highly useful for overcoming Cross-Origin Resource Sharing (CORS) restrictions and securely handling sensitive API keys by keeping them on the server. The client makes requests to the Node.js proxy, which then forwards them to the external API, adding authentication headers (like an API key) server-side and returning the response to the client. This approach keeps API keys out of the client-side code and allows communication with APIs that might otherwise block direct client requests.