JAVASCRIPT
Proxy External API to Bypass CORS and Secure Keys
Learn to create a Node.js proxy server to securely access external APIs, bypass CORS restrictions, and hide sensitive API keys from client-side code.
// server.js (Node.js with Express)
const express = require('express');
const axios = require('axios');
const cors = require('cors');
require('dotenv').config(); // For environment variables
const app = express();
const PORT = process.env.PORT || 3001;
// Enable CORS for client-side requests
app.use(cors());
app.use(express.json());
// 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 server-side
const externalApiUrl = 'https://api.example.com/data'; // Replace with actual API URL
const response = await axios.get(externalApiUrl, {
headers: {
'Authorization': `Bearer ${externalApiKey}`,
// Add other necessary headers for the external API
},
params: req.query // Pass client-side query parameters to external API
});
res.json(response.data);
} catch (error) {
console.error('Error proxying external API:', error.message);
res.status(error.response?.status || 500).json({
message: 'Failed to fetch external data',
error: error.message
});
}
});
app.listen(PORT, () => {
console.log(`Proxy server running on http://localhost:${PORT}`);
});
// Example .env file:
// EXTERNAL_API_KEY=your_secret_api_key_here
How it works: This Node.js Express server acts as a proxy for an external API. It allows your frontend application to make requests to `/api/external-data` which then securely fetches data from `https://api.example.com/data` on the server-side. This approach bypasses CORS issues, hides sensitive API keys from the client, and can add additional server-side logic or caching.