JAVASCRIPT
Simple Node.js Proxy for Third-Party APIs
Learn how to create a basic Node.js proxy server using Express to securely access third-party APIs from your frontend, bypassing CORS restrictions and hiding API keys.
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const PORT = process.env.PORT || 3000;
const TARGET_API_URL = 'https://api.example.com/data'; // Replace with your target API
const API_KEY = process.env.API_KEY; // Store API key securely in environment variables
app.use(express.json());
// Proxy endpoint
app.get('/api/proxy/data', async (req, res) => {
try {
const response = await fetch(TARGET_API_URL, {
headers: {
'Authorization': `Bearer ${API_KEY}`, // Example: add API key securely
'Content-Type': 'application/json'
// Add any other headers required by the target API
}
});
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' });
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates a simple proxy server using Express. It fetches data from a third-party API on behalf of your frontend, addressing common challenges like Cross-Origin Resource Sharing (CORS) and securely handling sensitive API keys. By routing requests through your backend, the API key remains server-side, never exposed to the client. This method enhances security and simplifies frontend API interaction.