JAVASCRIPT
Proxy Third-Party API Requests from Server (Node.js)
Learn how to create a Node.js Express server proxy to securely fetch data from third-party APIs, avoiding CORS issues and protecting API keys.
// server.js (Node.js with Express)
const express = require('express');
const fetch = require('node-fetch'); // or axios
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// Proxy endpoint for a hypothetical external API
app.get('/api/proxy/external-data', async (req, res) => {
try {
const externalApiUrl = 'https://api.example.com/data';
const apiKey = process.env.EXTERNAL_API_KEY; // Stored securely
const response = await fetch(externalApiUrl, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorData = await response.text();
console.error('External API error:', response.status, errorData);
return res.status(response.status).json({ error: 'Failed to fetch data from external API', details: errorData });
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Proxy server error:', error);
res.status(500).json({ error: 'Internal server error during proxy request' });
}
});
// Client-side call example (from your frontend):
// fetch('/api/proxy/external-data')
// .then(response => response.json())
// .then(data => console.log(data))
// .catch(error => console.error('Client fetch error:', error));
app.listen(PORT, () => {
console.log(`Proxy server running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to create a server-side proxy for third-party API requests. By routing client requests through your own backend, you can securely manage API keys, bypass Cross-Origin Resource Sharing (CORS) restrictions, and add additional server-side logic or caching. The client interacts only with your `/api/proxy/external-data` endpoint, and your server handles the actual call to the external API.